http://www.perlmonks.org?node_id=100568


in reply to Can you teach a new dog an old trick?

It's such a common idiom that the -p and -i command-line flags were invented to deal with it:

#!/usr/bin/perl -wpi s/string1/string2/g;

And then you'd run it as: myScript *.htm

update: note that the contents of a script run with -p or -n are inside a loop. If you want to initialize anything before the loop, use a BEGIN or INIT block.

Replies are listed 'Best First'.
Re: Re: Can you teach a new dog an old trick?
by PetaMem (Priest) on Jul 29, 2001 at 12:43 UTC
    This is not good...

    I tried to extend it to:

    #!/usr/bin/perl -wpi my $src = shift; my $dst = shift; s/$src/$dst/g;
    and it throws many many messages on me:
    Use of uninitialized value in substitution (s///) at /home/rj/bin/repl +ace line 4, <> line 38. Use of uninitialized value in regexp compilation at /home/rj/bin/repla +ce line 4, <> line 39. Use of uninitialized value in substitution (s///) at /home/rj/bin/repl +ace line 4, <> line 39. Use of uninitialized value in regexp compilation at /home/rj/bin/repla +ce line 4,
    (called "replace hallo hello tmp.txt")
    Then I looked at man perl what this switch -p does
    ok it was not there, so I looked at man perlrun and
    then I found the error (it tries to get $src and $dst in every
    loop. Well, I´m using my old replace script now again...
    #!/usr/bin/perl my $src = shift; my $dst = shift; print "Replace >$src< with >$dst<.\n"; $dst =~ s/\\n/\n/g; $dst =~ s/\\t/\t/g; foreach $file (@ARGV) { my $file2 = "/tmp/$file.".$$; print "replacing in File: $file...\n"; print "$file2\n"; open HANDLE, $file or die "$file: $!"; while(<HANDLE>) { $zeile .= $_; # Zeile von Datei einlesen } close HANDLE; $zeile =~ s/$src/$dst/gs; open HANDLE, ">$file2"; print HANDLE $zeile; close HANDLE; $zeile = ''; system("mv $file2 $file"); }
    Its ugly and unelegant and made 1996, but it works. :-)

    Ciao

      You need to use a BEGIN block, like so:

      #!/usr/bin/perl -wpi BEGIN { ($src,$dst)=(@ARGV); } s/$src/$dst/g;