Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

Simple array question

by Anonymous Monk
on Dec 22, 2003 at 16:57 UTC ( #316406=perlquestion: print w/replies, xml ) Need Help??

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

Hello all, I have the following code:
my @attrvals = (["customer", "20528"], ["priority", "3"]); print length(@attrvals);
The answer I get back is "1". Huh? I want an array with two elements each of which is an anonymous array. What am I doing wrong? Adam

Replies are listed 'Best First'.
Re: Simple array question
by thraxil (Prior) on Dec 22, 2003 at 17:04 UTC

    you want scalar not length.

    you use length to count the number of characters in a string.

Re: Simple array question
by BrowserUk (Pope) on Dec 22, 2003 at 17:09 UTC

    Try reading the documentation for length, (<< Click the link:).

    Once you have read that, you see that length is not used for determining the number of elements in an array in perl.

    You should then read the documentation on perls data types.

    After which you will find that changing length(@attrvals); to scalar @attrvals; will print the value "2" that you are expecting, but please read the second link above. If you don't, you won't understand why it works, and that will result in your encountering similar confusion very quickly.

    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail

Re: Simple array question
by davido (Cardinal) on Dec 22, 2003 at 17:21 UTC
    Evaluating an array in scalar context will tell you how many elements the array contains. length is not the right tool for the job.

    my @array = (["customer", "20528"], ["priority", "3"]); print scalar @array;

    It's an easy (and common) mistake to make.


Re: Simple array question
by Roger (Parson) on Dec 23, 2003 at 01:01 UTC
    I just want to add why you are printing the value of '1', other monks have already pointed out a fix to your problem.

    Your code, print length(@attrvals); is equivalent to print length( scalar @attrvals );, which is equivalent to print length("2"), which prints "1", the length of string "2".

    Run the demo code below -
    my @array = 0..99; # 100 element array print length(@array);
    The output is 3, since the string "100" (elements) has 3 characters.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://316406]
Approved by coreolyn
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (2)
As of 2021-02-27 10:38 GMT
Find Nodes?
    Voting Booth?

    No recent polls found