Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Re: general perl question

by repson (Chaplain)
on Apr 24, 2001 at 15:17 UTC ( #75018=note: print w/replies, xml ) Need Help??

in reply to In-place editing of files (was: general perl question)

If your program is not being run on the command line you could use code similar to this.
my $filename = 'foo.txt'; open IN, "< $filename" or die "Can't open $filename: $!\n"; open OUT, "> $filename.bak" or die "Can't write to $filename: $!\n"; while (<IN>) { s/foo/blah/g; print OUT $_; } close IN; close OUT; rename "$filename.bak", $filename;
However this code is only the barest code that will work, and should probably not be used without file locks and other sanity checks.

Replies are listed 'Best First'.
Re: Re: converting files in place
by petdance (Parson) on Apr 24, 2001 at 17:37 UTC
    The flags work without the command line, too. The following will convert any files specified on the command line to all caps.
    #!/usr/bin/perl -w -i.bak -p $_ = uc;
    In fact, there was an Obfuscated Perl contest entry a while back that does DOS-to-Unix conversions using only command line switches on the shebang line.


    # Andy Lester  AIM:petdance
    %_=split';','.; Perl ;@;st a;m;ker;p;not;o;hac;t;her;y;ju';
    print map $_{$_}, split //,
      What I meant was that my code can be dropped in the middle of a program, while to use the switches in the middle of a program you would have to spawn a new perl with those switches.
      #!/usr/bin/perl -w ..... system(q#perl -i.bak -p -e '$_ = uc'#); .....

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (8)
As of 2016-10-27 21:43 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (371 votes). Check out past polls.