http://qs321.pair.com?node_id=710067

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.