Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
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
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.

    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 romping around the Monastery: (12)
As of 2015-07-28 16:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (258 votes), past polls