Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

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 all is quiet...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (5)
As of 2018-03-18 11:00 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (230 votes). Check out past polls.