Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

array splice vs hash splice

by kiat (Vicar)
on Jun 05, 2005 at 02:24 UTC ( [id://463631]=perlquestion: print w/replies, xml ) Need Help??

kiat has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

Just out of curiosity...

An array is prefixed with @ and so when you want to do an array splice, you also use @ to get to the elements:

my @array = qw(one two three four five); print "@array[2,3]\n"; # prints three four
A hash is prefixed with % but why is a hash splice prefixed with @ and not %?
my %hash = ( 1 => 'one', 2 => 'two', 3 => 'three', 4 => 'four', 5 => 'five', ); print "@hash{'2', '3'}\n"; # prints two three
Hope someone can enlighten me.

Thanks in advance.

Replies are listed 'Best First'.
Re: array splice vs hash splice
by chas (Priest) on Jun 05, 2005 at 02:37 UTC
    It's actually a "slice". @ is used because the returned value is a list. (A hash is not really printable in its native form - only the associated list is printable in a way readable by humans. That's probably why hashes don't interpolate in double quoted strings - it doesn't make much sense.)
    chas
Re: array splice vs hash splice
by Zaxo (Archbishop) on Jun 05, 2005 at 03:14 UTC

    Expanding on chas's excellent reply, a hash slice is a list of values from the hash. It is just as suitable for assignment to an array as keys or values, and just as unsuitable for assignment to a hash.

    After Compline,
    Zaxo

Re: array splice vs hash splice
by brian_d_foy (Abbot) on Jun 05, 2005 at 03:26 UTC

    I tell my students, and they typically don't have problems recognizing what is what when they think of it this way:

    When you see a $, you're dealing with one thing. When you see a @, you are dealing with zero or more things. You tell the variable type by what comes after it (nothing in scalars, square braces for arrays, braces for hashs).

    Sadly, this is going to change in Perl 6.

    --
    brian d foy <brian@stonehenge.com>

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (6)
As of 2024-04-23 09:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found