In perl (and many other scripting languages), printing intermediate values is a useful debugging technique. Setting up a small array and running it through your code will likely illuminate the problem ... cheers, drl
I am using print to debug my code but my problem here is logical...
In first element where condition is true, will delete (splice) the element and rest are pushed up in array. In immediate next run it will go to next element (as I am using foreach). So it will skip one element in this case....
---------- Post updated 10-29-09 at 01:39 AM ---------- Previous update was 10-28-09 at 10:20 PM ----------
I found one alternative here, that's "redo"... But again, having some loopholes...
Can anyone suggest a better solution here
#!/usr/bin/perl
# @(#) p1 Demonstrate splice element tracking.
use warnings;
use strict;
use feature qw(switch say);
use 5.010;
my ($debug);
$debug = 0;
$debug = 1;
my ( $cnt, $element );
my (@a) = qw/ a b c a z /;
print "\n";
print " Array as input :@a:\n\n";
# Original code.
$cnt = 0;
foreach $element (@a) {
if ( $element eq "a" ) {
splice( @a, $cnt, 1 );
print " Inside loop, a is :@a:\n";
}
else {
$cnt++;
}
}
print "\n Original, cnt = $cnt\n", " array = @a\n";
print "\n -----\n\n";
# Re-written code.
@a = qw/ a b c a z /;
$cnt = 0;
foreach $element (@a) {
if ( $element eq "a" ) {
splice( @a, $cnt, 1 );
print " Inside loop, a is :@a:\n";
}
$cnt++;
}
print "\n Modified, cnt = $cnt\n", " array = @a\n";
exit(0);
producing:
% ./p1
Array as input :a b c a z:
Inside loop, a is :b c a z:
Inside loop, a is :b a z:
Original, cnt = 1
array = b a z
-----
Inside loop, a is :b c a z:
Inside loop, a is :b c z:
Modified, cnt = 3
array = b c z