Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re^3: Array/List Strangeness

by ikegami (Patriarch)
on Aug 05, 2009 at 02:58 UTC ( [id://785957]=note: print w/replies, xml ) Need Help??


in reply to Re^2: Array/List Strangeness
in thread Array/List Strangeness

Again, I know *what* is happening. The question is *why*. Why does requesting an non-existing array element return undef and requesting an non-existing list element return nothing.

I have tried to avoid using the term "array" or "list" for these @vars. I remain curious as to when @var is an array and when @var is a list.

@var is an array. It evaluates to a list in list context, just like every other operator.

Replies are listed 'Best First'.
Re^4: Array/List Strangeness
by Taulmarill (Deacon) on Aug 05, 2009 at 09:45 UTC
    There is no such thing as a non-existing array element. Every element of an array, which has not been set to something else, will return the value undef. Even if you only use the first 10 elements of the array, all other elements are virtually existing and hold the value undef. Also, an array is evaluated as a list in list context, but this happens after the slicing. Compare the results of the following code:
    use Data::Dumper; my @foo = qw/a b c/; my @bar = $foo[3]; print Dumper \@bar; @bar = ( @foo )[3]; print Dumper \@bar;

      There is no such thing as a non-existing array element

      Yes, there is. An array with 5 undef values in it has size 5 and not unlimited size. And concatenating two arrays works only because the first array is not unlimited

        That's what Taulmarill meant.

        Basically: an "empty" array can have any size, but an empty list always has size 0.

        UPDATE: that should show it...

        DB<1> @a[3..5]=() DB<2> @b[3..5]=() DB<3> print scalar @a 6 DB<4> print ( () = @a,@b ) DB<5> @c= @a,@b DB<6> print scalar @c 6 DB<7> @c=(@a,@b) DB<8> print scalar @c 12 DB<9> print ( () = (@a,@b) ) DB<10> push @a,@b DB<11> print scalar @a 12 DB<12> x @a 0 undef 1 undef 2 undef 3 undef 4 undef 5 undef 6 undef 7 undef 8 undef 9 undef 10 undef 11 undef

        Line 12 clearly shows, that concatenating two "empty" arrays leads to a larger "empty" array...

        Anyway the difference between line 5 and 7 is somehow surprising ...

        UPDATE: Aaaaaargh!!! 8)

        In line 5, I fell into the scalar comma operator trap again ... it's basically (@c=@a),(@b)

        Cheers Rolf

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2024-04-19 03:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found