jbert has asked for the wisdom of the Perl Monks concerning the following question:
Hi Monks,
This surprised me in code recently:
#!/usr/bin/perl use strict; use warnings; use Data::Dumper qw(Dumper); my @a = qw(1 2 3); print "Initially: " . Dumper(\@a); my @b = @a[0..5]; print "After assign from: " . Dumper(\@a); @b = grep { defined $_ } @a[0..5]; print "After grep over: " . Dumper(\@a); # Didn't expect the undef's
Well, I actually ran into the issue with a foreach loop rather than a grep. 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.
Does anyone have a nice, concise syntax for looping over "the first N elements of an array, without vivification"?
The best I can think of is:
my @b = @a[0..N-1]; foreach my $val (@b) { .... }
which has the wart of requiring the additional variable @b.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Avoiding vivification with array slice
by betterworld (Curate) on Sep 09, 2008 at 12:57 UTC | |
by jbert (Priest) on Sep 09, 2008 at 13:45 UTC | |
Re: Avoiding vivification with array slice
by moritz (Cardinal) on Sep 09, 2008 at 12:45 UTC | |
Re: Avoiding vivification with array slice
by jhourcle (Prior) on Sep 09, 2008 at 14:04 UTC | |
by jbert (Priest) on Sep 09, 2008 at 14:45 UTC | |
by ikegami (Patriarch) on Sep 09, 2008 at 19:45 UTC | |
Re: Avoiding vivification with array slice
by Narveson (Chaplain) on Sep 09, 2008 at 14:05 UTC | |
Re: Avoiding vivification with array slice
by Anonymous Monk on Sep 09, 2008 at 13:49 UTC | |
by jbert (Priest) on Sep 09, 2008 at 14:40 UTC |
Back to
Seekers of Perl Wisdom