Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Re: Avoiding vivification with array slice

by jhourcle (Prior)
on Sep 09, 2008 at 14:04 UTC ( #710092=note: print w/replies, xml ) Need Help??

in reply to Avoiding vivification with array slice

I was thinking that the defined test would exclude any bits of the slice I didn't want - with no side effects. But clearly reading the value to test it's defined-ness is enough to vivify.

You're testing too late. Besides betterworld's trick, or moritz's optimization, you could specifically test for defined-ness per element, rather than taking the slice first:

@b = map { defined($a[$_]) ? ($a[$_]) : () } (0..5);

Replies are listed 'Best First'.
Re^2: Avoiding vivification with array slice
by jbert (Priest) on Sep 09, 2008 at 14:45 UTC

    Cool. Accessing $a[$i] isn't enough to vivify (otherwise your defined test would do it).

    So we don't actually need the defined test in your map and can get away with:

    # This *doesn't* vivify $a[3,4,5] @b = map { $a[$_] } (0..5);


      The point of the defined wasn't to prevent autovivification, but to implement the grep you had in your original code. The following two snippets are equivalent.
      @b = map { defined($a[$_]) ? ($a[$_]) : () } 0..5;
      @b = grep { defined } map { $a[$_] } 0..5;

      What you suggested (@b = map { $a[$_] } 0..5;) is *not* equivalent.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (9)
As of 2016-10-24 08:33 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (304 votes). Check out past polls.