Philip Davies
2018-08-13 19:29:52 UTC
Hi,
I'm trying to understand why there is a difference in output between the two loops in the sample code below.
#!/usr/bin/perl
use strict;
use warnings;
my @array = (1, 3, 5, 7, 11);
my $number = 6;
#---------------------------------------------------------------------
my $index = undef;
LOOP1: for ($index = 0; $index <= $#array; $index++)
{
print $index," - ",$array[$index],"\n";
last LOOP1 if ($number < $array[$index]);
}
print "index = ",$index,"\n";
print STDERR "\n";
#---------------------------------------------------------------------
$index = undef;
LOOP2: foreach $index (0..$#array)
{
print $index," - ",$array[$index],"\n";
last LOOP2 if ($number < $array[$index]);
}
print "index = ",$index,"\n";
#---------------------------------------------------------------------
exit 0;
When run the output is:-
# ./test.pl
0 - 1
1 - 3
2 - 5
3 - 7
index = 3
0 - 1
1 - 3
2 - 5
3 - 7
Use of uninitialized value $index in print at ./test.pl line 29.
index =
Having declared $index outside both loops, I would have expected that $index would retain its last value in the second loop. Any pointers to where in the perl documentation I should be looking would be most appreciated.
Cheers
Phil
I'm trying to understand why there is a difference in output between the two loops in the sample code below.
#!/usr/bin/perl
use strict;
use warnings;
my @array = (1, 3, 5, 7, 11);
my $number = 6;
#---------------------------------------------------------------------
my $index = undef;
LOOP1: for ($index = 0; $index <= $#array; $index++)
{
print $index," - ",$array[$index],"\n";
last LOOP1 if ($number < $array[$index]);
}
print "index = ",$index,"\n";
print STDERR "\n";
#---------------------------------------------------------------------
$index = undef;
LOOP2: foreach $index (0..$#array)
{
print $index," - ",$array[$index],"\n";
last LOOP2 if ($number < $array[$index]);
}
print "index = ",$index,"\n";
#---------------------------------------------------------------------
exit 0;
When run the output is:-
# ./test.pl
0 - 1
1 - 3
2 - 5
3 - 7
index = 3
0 - 1
1 - 3
2 - 5
3 - 7
Use of uninitialized value $index in print at ./test.pl line 29.
index =
Having declared $index outside both loops, I would have expected that $index would retain its last value in the second loop. Any pointers to where in the perl documentation I should be looking would be most appreciated.
Cheers
Phil