Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Avoiding vivification with array slice

by jhourcle (Prior)
on Sep 09, 2008 at 14:04 UTC ( [id://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);

    Thanks.

      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?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2024-04-24 20:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found