Click to See Complete Forum and Search --> : Perl, why can't I do this?
MrNewbie
12-09-2001, 02:12 PM
Here's a piece of my perl code, I'm supposed to be reading a number from a file, incrementing it, and writing it back to the file.
if(open(FILE, "+>file.txt")){
my $var = <FILE>;
print "Here, var = $var\n";
$var++;
print "Here, var = $vart\n";
seek(FILE, 0, 2);
print FILE "$var";
close FILE;
}
else{
print "Error opening file";
}
With the
print "Here, var = $var\n";
$var++;
print "Here, var = $vart\n";
The first use of $var causes an error due to the use of an uninitialized variable.
What am I doing wrong? I just can't see it.
Thanks
klamath
12-09-2001, 06:37 PM
I think if you have a file open for output, you can't read from it; vice-versa for writing to a file opened for input.
MrNewbie
12-09-2001, 07:11 PM
Isn't opening it like this:
open(FILE, "+>file.txt");
Opening for reading and writing?
iDxMan
12-09-2001, 07:47 PM
Why don't you make 2 passes at it.
#!/usr/bin/perl
$file = "foo";
open(FILE,"<$file") or die "Error opening $file\n$!\n";
$var = <FILE>;
close(FILE);
$var =~ tr/0-9.//cd;
++$var;
open(FILE,">$file") or die "$!";
print FILE $var;
close(FILE);
MrNewbie
12-09-2001, 08:00 PM
I'm going to have too, thanks. I'm confused about what this does though.
$var =~ tr/0-9.//cd;
Drops anything that isn't a number?
takshaka
12-09-2001, 10:26 PM
Originally posted by MrNewbie:
if(open(FILE, "+>file.txt")){
perldoc -f open (http://www.perldoc.com/perl5.6.1/pod/func/open.html)
As the docs say, this clobbers the file every time. <FILE> returns undef on an empty file, thus the warning.
If you want to open in read/write mode and automatically create the file if it doesn't exist, you'll need to use sysopen() with the O_RDWR and O_CREAT flags.
perldoc -f sysopen (http://www.perldoc.com/perl5.6.1/pod/func/sysopen.html)
perldoc perlopentut (http://www.perldoc.com/perl5.6.1/pod/perlopentut.html)
print "Here, var = $vart\n";
Typo.
use strict;
seek(FILE, 0, 2);
That sets the filehandle's position to end-of-file. There must be a way to set it to the beginning of a file. If only someone would write down how to do that...
perldoc -f seek (http://www.perldoc.com/perl5.6.1/pod/func/seek.html)
iDxMan
12-11-2001, 12:05 AM
Originally posted by MrNewbie:
<STRONG>I'm going to have too, thanks. I'm confused about what this does though.
$var =~ tr/0-9.//cd;
Drops anything that isn't a number?</STRONG>
Just translates anything that's not a number or period out of the string. There for sanity and then some...
-r