Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: What's the construction?

by halfcountplus (Hermit)
on Sep 15, 2011 at 11:06 UTC ( [id://926118]=note: print w/replies, xml ) Need Help??


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
    This is kind of a nicer way to deal with parameters since you can provide them in any order...

    While I agree named parameters are nice and, indeed, recommended in some cases by such sources as TheDamian's Perl Best Practices (PBP), this particular approach to named parameters is questionable (in the extreme IMO) because it allows one to arbitrarily add an element to the function argument list (or, in some cases, to drop one) without anyone being the wiser. This sort of 'niceness' has 'accident waiting to happen' and '3AM debug session' written all over it. If there is any valid reason for this particular nicety (and it's hard to imagine one), it should, as pointed out below by Anonymonk, be thoroughly documented – and then should probably be eliminated at the first code review.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://926118]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (2)
As of 2024-04-19 18:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found