Hendrik Maryns wrote:
John W. Krahn schreef:

You can do both in a single loop like this:

tie my @bestand, 'Tie::File', $best or die "Kon het bestand niet binden: ", $!;

for ( reverse 0 .. $#bestand ) {
    $bestand[ $_ ] =~ s{\[\d+/\d+/\d+\s\d+:\d+\]\s}{};
    splice @bestand, $_, 1 if $bestand[ $_ ] !~ /^<.*>/;
}

Note that you have to start at the end of the array for splice() to remove the correct element.

Can you explain this a bit further? I read about splice in the perlop page, but don't quite see through it yet.

Suppose that you have an array:

# index         0 1 2 3 4 5 6 7
my @array = qw/ a b c d e f g h /;

And you loop through it starting with the first element:

for ( 0 .. $#array ) {

And you want to remove the element 'c':

    splice @array, $_, 1 if $array[ $_ ] eq 'c';


The for(each) loop creates a list (0,1,2,3,4,5,6,7) and iterates through that list setting $_ to the value of each element of that list. When $_ == 2 and $array[2] eq 'c' then splice() will remove that element from @array and now $array[2] eq 'd' and $array[3] eq 'e', etc. In other words, all the elements after 'c' move "down" and the array is shortened by one element. In the next iteration of the loop $_ becomes 3 and the contents of $array[2] (which used to be $array[3]) are missed by the test in the loop. Perhaps this example may help:


$ perl -le'
my @array = ( q/c/ ) x 8;
for ( 0 .. $#array ) {
    splice @array, $_, 1 if $array[ $_ ] eq q/c/;
    }
print @array . "  @array";
'
4  c c c c

However, if you reverse the list:

$ perl -le'
my @array = ( q/c/ ) x 8;
for ( reverse 0 .. $#array ) {
    splice @array, $_, 1 if $array[ $_ ] eq q/c/;
    }
print @array . "  @array";
'
0

You can see that every element was seen and removed by splice().


Another method is to use the in-place edit variable along with the @ARGV array
although this method does not really edit the file "in-place".


{ local ( $^I, @ARGV ) = ( '', <*.log> );

    while ( <> ) {
       s{\[\d+/\d+/\d+\s\d+:\d+\]\s}{};
        next unless /^<.*>/;
        print;
    }
}

What does $^I do? "The current value of the inplace-edit extension. Use undef to disable inplace editing. (Mnemonic: value of -i switch.)" isn't really helpful, I'm afraid.

No it isn't. That is because it is described in perlrun.pod under the entry for the -i switch.


perldoc perlrun



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