James Turnbull wrote:
> Hi all
Hello,
> This feels like a really dumb question but doing a regex find and
> replace is it possible to delete a line? For example,
>
> for (@file) {
> s/foo//g;
> }
>
> which equates to:
>
> for each element in array 'file' if you find 'foo' then replace it with
> null.
>
> I then write the array to a file (using Tie::File) and it leaves a blank
> line where the element containing 'foo' was like:
>
> null
> foo1
> foo2
> foo3
>
> Perhaps I am confabulating two ideas here? Is there a way to walk
> through an array and find a particular array element and delete it
> rather than replace it with null (and then write it out to a file using
> Tie::File)?
As you have seen when using Tie::File removing the contents of a line do not
remove that line. You have to splice the tied array:
my $line_to_remove;
for my $i ( 0 .. $#file ) {
$line_to_remove = $i if /foo/;
}
splice @file, $line_to_remove, 1;
If you have more than one line to remove:
my @lines_to_remove;
for my $i ( 0 .. $#file ) {
unshift @lines_to_remove, $i if /foo/;
}
for ( @lines_to_remove ) {
splice @file, $_, 1;
}
And if you want to do it with one loop:
for my $i ( reverse 0 .. $#file ) {
splice @file, $i, 1 if /foo/;
}
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>