我有一个脚本如下:
$x=1;
$y=2;
@test=($x,$y);
foreach (@test)
{
print;
print "\n";
}
它给我的输出为:
1 2
但我希望输出与占位符相关联,例如:
$x = 1 $y = 2
有人可以提供一些提示吗?
您不要将变量放入数组中;它包含值。当您分配变量或将其放入数组时,此值将被复制。我们可以证明这一点:
$x = 1;
$y = $x; # here a copy
$x = 42; # reassigns $x, does not change $y
print "$x\n"; # 42
print "$y\n"; # 1
当我们将$x
和$y
放入数组时也会发生同样的事情:它现在只包含以前的值。没有办法找出它们来自哪些变量。
数组是事物的编号集合。还有另一个有趣的数据结构:散列。哈希是带有标签的事物的低级集合。我们可以使用标签来访问值$hash{$label}
,就像我们可以通过索引访问数组中的事物一样$array[$index]
。
该keys
函数返回哈希的所有标签的列表,并且该sort
函数按字母顺序排列列表。
我们可以创建一个像
%hash = (
x => $x, # the label "x" has the value of $x, but copied
y => $y,
);
现在我们可以像这样打印所有这些了
foreach (sort keys %hash) {
print "$_ = $hash{$_}\n";
}
但是因为我们编写了现代 Perl,所以我们use strict; use warnings;
声明了我们所有的变量,并且use 5.010
(或更高,因为 perl 没有完全过时,所以我们可以使用该say
函数)。然后我们可以这样做:
use strict; use warnings; use 5.010;
my $x = 1;
my $y = 2;
my %hash = (
x => $x,
y => $y,
);
for my $key (sort keys %hash) {
say "$key = $hash{$key}"; # say is like print, but adds a newline
}
输出:
x = 1
y = 2
您可以使用哈希来执行此操作:
#!/usr/bin/perl
use warnings;
use strict;
my %test = ( x => '1',
y => '2');
while ( my ($key, $value) = each(%test) ) {
print "$key => $value\n";
}
输出:
y => 2
x => 1
@user2684591
由于问题指向数组 -
$x=1;
$y=2;
@test=($x,$y);
for my $i (0 .. $#test) {
print "\$test[$i]: $test[$i]\n";
}