Perl Hash Slice, Replication x Operator, and sub params
Posted
by user210757
on Stack Overflow
See other posts from Stack Overflow
or by user210757
Published on 2010-06-03T20:54:55Z
Indexed on
2010/06/03
21:04 UTC
Read the original article
Hit count: 308
Ok, I understand perl hash slices, and the "x" operator in Perl, but can someone explain the following code example from here (slightly simplified)?
sub test{
my %hash;
@hash{@_} = (undef) x @_;
}
Example Call to sub:
test('one', 'two', 'three');
This line is what throws me:
@hash{@_} = (undef) x @_;
It is creating a hash where the keys are the parameters to the sub and initializing to undef, so:
%hash:
'one' => undef, 'two' => undef, 'three' => undef
The rvalue of the x operator should be a number; how is it that @_ is interpreted as the length of the sub's parameter array? I would expect you'd at least have to do this:
@hash{@_} = (undef) x length(@_);
© Stack Overflow or respective owner