Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In-place editing of multiple files in a directory using Perl's diamond and in-place edit operator

Tags:

perl

I am trying to in-place edit a bunch of text files using Perl's in-place edit operator $^I. I traverse through the directory using the diamond (<>) operator like this:

$^I = ".bak";

@ARGV = <*.txt>;

while (<>)
{
    s/((?:^|\s)-?)(0+)(?=\s|$)/$1.$2/g;
    print;
}

This works perfectly and does the job I need it to do. But what if my @ARGV is already populated with some other data I need for the program? I tried to do the following:

$^I = ".bak";

my @files = <*.txt>;

while (<@files>)
{
    s/((?:^|\s)-?)(0+)(?=\s|$)/$1.$2/g;
    print;
}

But it does not work. What I am I missing here? I can't use my $ARGV as it contains other data and can't mess it with file matching patterns.

Any suggestions?

Thanks!

like image 281
Golam Kawsar Avatar asked Dec 28 '22 06:12

Golam Kawsar


2 Answers

You can copy your arguments beforehand, and then use @ARGV. E.g.:

my @args = @ARGV;
@ARGV = <*.txt>;

Since there is some hidden processing going on, which is specific to the use of @ARGV and the diamond operator <>, you cannot just use another array to do the same thing.

like image 104
TLP Avatar answered Dec 29 '22 19:12

TLP


You can give @ARGV a temporary value with the local keyword:

{
    local @ARGV = <*.txt>;
    while (<>) {...}
} # @ARGV gets the old value back
like image 26
Eric Strom Avatar answered Dec 29 '22 18:12

Eric Strom