Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Can you teach a new dog an old trick?

by bikeNomad (Priest)
on Jul 28, 2001 at 20:40 UTC ( [id://100568]=note: print w/replies, xml ) Need Help??


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;

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://100568]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (4)
As of 2025-07-08 05:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.