Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

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);


Comment on Re: Avoiding vivification with array slice
Download Code
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
Node Status?
node history
Node Type: note [id://710092]
help
Chatterbox?
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: (16)
As of 2014-12-18 18:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (59 votes), past polls