2014-09-23 69 views
0

我在其他语言中看到了相当于PHP's compact function的问题,但不包含Perl,所以请原谅我,如果这是我错过的东西的重复。如果你不熟悉这个功能,这是我正在寻找的。Perl的等价PHP的compact()?

鉴于变量:

my $one = "1"; 
my $two = "2"; 
my $three = "3"; 

#using compact as example here since this function doesn't exist in perl 
my $array = compact("one","two","three"); 

然后倾倒$阵列将给予:

[ 
    one => "1, 
    two => "2", 
    three => "3" 
] 

PHP documentation for compact

创建一个包含变量及其值的数组。

对于其中的每一个,compact()都会在当前符号表中查找具有该名称的变量,并将其添加到输出数组中,以便变量名称变为关键字,并且该变量的内容将成为该关键字的值。

我特别使用5.8.8版本。原谅我,如果我的一些语法关闭。我的背景是PHP。

+3

什么是你要完成的,需要紧凑的()? – 2014-09-23 20:11:37

+2

我可能会误解,但看起来很像[将变量用作变量名称](http://perl.plover.com/varvarname.html)。呸。 – ThisSuitIsBlackNot 2014-09-23 20:12:03

+2

幸运的是,在perl中没有这个相同的东西,这对于一种语言来说似乎是一件可怕的事情。如果你解释你想做什么而不是你想做什么,这里的某个人可能会帮助你获得更好的解决方案(可能涉及哈希)。 – AKHolland 2014-09-23 20:19:14

回答

1

相反的:

my $one = "1"; 
my $two = "2"; 
my $three = "3"; 

#using compact as example here since this function doesn't exist in perl 
my $array = compact("one","two","three"); 

可能你想:

use strict; 
use warnings; 
use feature 'say'; 
use Data::Dumper; 

my $numbers = { 
    one => 1, 
    two => 2, 
    three => 3, 
}; 

say Dumper $numbers; 
my $sum = $numbers->{one} + $numbers->{two}; 
say $sum; 
0

如果变量声明为包变量(如$::one = 1our $one = 1),那么它可能做到这一点通过检查符号表。不过,我强烈建议不要这样做。我一直在编程Perl超过20年,我从来没有这样做过。代之以使用散列。

请不要这样做。但是如果你陷入困境并且真的很难找到解决方案,那么就是一个解决方案。它只适用于声明为包变量的简单标量值(如您的示例中)。

my %hash = map { $_ => ${$::{$_}} } qw{one two three}; 

或者:

sub compact { +{ map { $_ => ${$::{$_}} } @_ } } 

my $hashref = compact("one", "two", "three");