For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > November 2007 > Explaination









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Explaination
AndrewMcHorney

2007-11-22, 7:00 pm

Hello

Can someone the reasoning why it is technically correct that when
extracting a scalar item from an array that one must use
$array_name[$index] instead of @array_name[$index] ? To me, the
logical way is to use the array name with the symbol of array. It is
my understanding that using $var_name = $@array_name[$index] will
produce an array of one item. I would think it would produce a
string. I would think that if you wanted an array of 1 item you would
do @new_array = $@array_name[$index].

Thanks,
Andrew

Tom Phoenix

2007-11-22, 7:00 pm

On 11/21/07, AndrewMcHorney <andrewmchorney@cox.net> wrote:

> Can someone the reasoning why it is technically correct that when
> extracting a scalar item from an array that one must use
> $array_name[$index] instead of @array_name[$index] ?


Reasoning don't come in cans. :-)

When one codes as you did, the perldiag manpage opines:

You've used an array slice (indicated by @) to select a single
element of an array. Generally it's better to ask for a scalar
value (indicated by $). The difference is that $foo[&bar] always
behaves like a scalar, both when assigning to it and when evaluating
its argument, while @foo[&bar] behaves like a list when you assign
to it, and provides a list context to its subscript, which can do
weird things if you're expecting only one subscript.

In other words, it's a matter of context. The sigil tells Perl (and
everyone else) whether you mean singular or plural, and it matters
which you mean. The difference in meaning is akin to that between
"Moving pianos is dangerous" and "Moving pianos are dangerous".

Cheers!

--Tom Phoenix
Stonehenge Perl Training
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com