Tova Yaron wrote:
> Hello,

Hello,

>  Trying to remove from array blank lines, its look like splice get 
>  confuse with the array size after removing the blank entry.
>  Or maybe I'm getting confuse..
>  
>  
>  use strict;
>  
>  my   ($str0, $str1, $str2, $str3, $str4, $str5, $str6, $str7, $str8,
>  $str9,)
>               =
>       (
>        "000000000000000000000000000000000",
>        "111111111111111111111111111111111",
>        "222222222222222222222222222222222",
>        "333333333333333333333333333333333",
>        "444444444444444444444444444444444",
>        "",
>        "",
>        "",
>        "",
>        "999999999999999999999999999999999",
>       );
>  
>  my $ref_array = [ $str0, $str1, $str2, $str3, $str4, $str5, $str6, 
>  $str7, $str8, $str9,];
>  
>  foreach my $indx (0..$#$ref_array) {

foreach creates the list:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9

and iterates over it putting each value in turn into $indx.  The list is not
affected by changes to the array @$ref_array.


>       if ($ref_array->[$indx] =~ /^$/) {
>               splice (@$ref_array, $indx, 1);

splice removes elements from @$ref_array making it shorter.  At the first
empty line $indx contains 5 so $ref_array->[5] is removed from the array and
the array becomes:

'00...', '11...', '22...', '33...', '44...', '', '', '', '99...'

At the next iteration of the loop $indx is 6.  What was at $ref_array->[6]
before is now at $ref_array->[5] so one empty line is missed.  The empty line
at $ref_array->[6] is removed and the array becomes:

'00...', '11...', '22...', '33...', '44...', '', '', '99...'

At the next iteration of the loop $indx is 7 and $ref_array->[7] now contains
the line '999999999999999999999999999999999' so two empty lines are missed.


>       }
>  }
>  
>  foreach my $indx (0..$#$ref_array) {
>       print $ref_array->[$indx] . "\n";
>  }
>  
>  exit (0);

The correct way to do what you want is to start at the end of the array and
iterate backwards:

my $ref_array = [
    '000000000000000000000000000000000',
    '111111111111111111111111111111111',
    '222222222222222222222222222222222',
    '333333333333333333333333333333333',
    '444444444444444444444444444444444',
    '',
    '',
    '',
    '',
    '999999999999999999999999999999999',
    ];


for my $indx ( reverse 0 .. $#$ref_array ) {
    unless ( length $ref_array->[ $indx ] ) {
        splice @$ref_array, $index, 1;
        }
    }

for ( @$ref_array ) {
    print "$_\n";
    }

exit 0;


You could also use a C style for loop:

for ( my $indx = $#$ref_array; $indx >= 0; --$indx ) {
    unless ( length $ref_array->[ $indx ] ) {
        splice @$ref_array, $index, 1;
        }
    }




John
-- 
use Perl;
program
fulfillment

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to