in reply to What's the construction?
If you assign the values in an array to a hash, they form key-value pairs.
#!/usr/bin/perl use strict; use warnings FATAL => qw(all); my @ray = qw(a b c d e f); my %hash = @ray[0..3]; while (my ($k, $v) = each (%hash)) { print "$k = $v\n"; }
So $hash{a} = 'b'. Since I used an array slice (0..3), only the first four elements of @ray were used. You must have an even number of elements in the array you assign to the hash.
$# is the index of the last element of an array, so the slice in your example makes sure that the array has an even number of elements (the first element is 0, so if the last index is odd, that's an even number of elements, like 0 1 2 3; % is the modulus operator so $#_ % 2 will be 0 if $#_ is even, -1 to make it odd).
The argument stack to a subroutine is often processed this way so you can do stuff like this:
someSubRoutine (a => 1, b => 'foo', bar => 6);
If someSubRoutine() opens with a line like your example, %args is now that hash. This is kind of a nicer way to deal with parameters since you can provide them in any order, and if %args were like this:
my %args = ( a => 666, b => 'foo', @_ # or the modulus slice );
Predefine defaults that will be over-ridden, eg, if you pass "a => 999".
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: What's the construction?
by AnomalousMonk (Archbishop) on Sep 15, 2011 at 15:43 UTC |