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

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.


Comment on Re: general perl question
Download Code
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.

    xoxo,
    Andy

    # Andy Lester  http://www.petdance.com  AIM:petdance
    %_=split';','.; Perl ;@;st a;m;ker;p;not;o;hac;t;her;y;ju';
    print map $_{$_}, split //,
    'andy@petdance.com'
    
      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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (3)
As of 2014-08-31 03:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (294 votes), past polls