在 perl 中获取字符串的 hahes 键
get hahes key to string in perl
我不明白为什么 $test 是“1”而不是 'foo'。有什么办法可以把'foo'(用%hash写的)写到$test?
#/usr/bin/perl
use warnings;
use strict;
use utf8;
my %hash;
$hash{'test'} = {'foo' => 1};
print keys %{$hash{'test'}}; #foo
print "\n";
print values %{$hash{'test'}}; #1
print "\n";
print %{$hash{'test'}}; #foo1
print "\n";
# here is the part I do not understand
my $test = keys %{$hash{'test'}};
print "$test\n"; #1 but why? I was expecting #foo
如何在 $test 中推送 'foo'?
keys()
returns 一个列表。但是您对标量 (my $test = keys ...
) 的分配将其置于标量上下文中。因此,它被评估为列表的长度,在您的情况下为 1
。
my $test = keys %{$hash{'test'}};
将 keys
returns 这样的列表分配给标量时,分配的是列表的长度。在这种情况下是 1。
当 Perl 函数的 return 值让您感到困惑时,总是值得检查该函数的文档 - 特别注意讨论 return 值在不同上下文中如何变化的部分.
perldoc -f keys 的开头是这样说的(强调我的):
keys HASH
keys ARRAY
Called in list context, returns a list consisting of all the keys of the named hash, or in Perl 5.12 or later only, the indices of an array. Perl releases prior to 5.12 will produce a syntax error if you try to use an array argument. In scalar context, returns the number of keys or indices.
您正在将表达式的结果分配给标量变量。因此,该表达式在标量上下文中进行评估,您将获得散列中的键数(即 1)。
要解决此问题,请通过在变量周围放置括号来强制在列表上下文中计算表达式:
my ($test) = keys %{$hash{'test'}};
我不明白为什么 $test 是“1”而不是 'foo'。有什么办法可以把'foo'(用%hash写的)写到$test?
#/usr/bin/perl
use warnings;
use strict;
use utf8;
my %hash;
$hash{'test'} = {'foo' => 1};
print keys %{$hash{'test'}}; #foo
print "\n";
print values %{$hash{'test'}}; #1
print "\n";
print %{$hash{'test'}}; #foo1
print "\n";
# here is the part I do not understand
my $test = keys %{$hash{'test'}};
print "$test\n"; #1 but why? I was expecting #foo
如何在 $test 中推送 'foo'?
keys()
returns 一个列表。但是您对标量 (my $test = keys ...
) 的分配将其置于标量上下文中。因此,它被评估为列表的长度,在您的情况下为 1
。
my $test = keys %{$hash{'test'}};
将 keys
returns 这样的列表分配给标量时,分配的是列表的长度。在这种情况下是 1。
当 Perl 函数的 return 值让您感到困惑时,总是值得检查该函数的文档 - 特别注意讨论 return 值在不同上下文中如何变化的部分.
perldoc -f keys 的开头是这样说的(强调我的):
keys HASH
keys ARRAYCalled in list context, returns a list consisting of all the keys of the named hash, or in Perl 5.12 or later only, the indices of an array. Perl releases prior to 5.12 will produce a syntax error if you try to use an array argument. In scalar context, returns the number of keys or indices.
您正在将表达式的结果分配给标量变量。因此,该表达式在标量上下文中进行评估,您将获得散列中的键数(即 1)。
要解决此问题,请通过在变量周围放置括号来强制在列表上下文中计算表达式:
my ($test) = keys %{$hash{'test'}};