Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: How do you save a perl script?

by epoptai (Curate)
on Mar 24, 2001 at 07:29 UTC ( [id://66822]=note: print w/replies, xml ) Need Help??


in reply to How do you save a perl script?

It's a bad idea to save the count in the script, but it can be done. I wrote a CGI script to do this while exploring some other confusion.

Here are two console scripts. The first does the wrong thing by saving the count in itself. The second does the right thing by using an external data file.

As always in Perl, there are many other ways to increment a count. Neither of these two examples is the worst or best way to do it, they're merely bad and better.

WRONG

#!perl -w # self-contained counter script increments and prints value in DATA # set permissions to allow script to read and write itself - epoptai use strict; my$e = 0; my$d; while(<DATA>){$d .= $_} # read data $d++; # increment open (ME,"+>> $0") or die "$!"; # open self unless($^O=~/mswin/i){ flock(ME,2) or die "$!"} # lock unless win32 my@me = <ME>; # read self into array for(@me){ if($_=~m|_\_DATA_\_|){ $e = 1; next } # find last line if($e == 1){ $_ =~ s/\d+/$d/o } # and replace with incremented val +ue } seek ME, 0, 0; # goto top of self truncate ME, 0; # and clear it print ME @me; # write modified contents close ME or die "$!"; print $d; # print incremented value __DATA__ 0

RIGHT

#!perl -w # counter script increments and prints value in $file # set permissions to allow script to read and write $file - epoptai use strict; my$file = 'count.txt'; open (FILE,"+>> $file") or die "$!"; # open file unless($^O=~/mswin/i){ flock(FILE,2) or die "$!"} # lock unless win32 local $/ = undef; my$num = <FILE>; # read file into array $num++; seek FILE, 0, 0; # goto top of file truncate FILE, 0; # and clear it print FILE $num; # write modified contents close FILE or die "$!"; print $num; # print incremented value

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (3)
As of 2024-04-16 23:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found