You need to open the file $filename before you can read it. I suspect you wanted to do somethings like ...
open( MYFILE, "<$filename") or die ...
...
while ( my $line = <MYFILE> ) {
...
| [reply] [d/l] [select] |
Thanks! can you please look at the updated code and see where the error is? i saw that i made that mistake but still i am facing the same error
| [reply] |
foreach my $filename( @files ){
my $file = "text_000".$variable."."."lab";
my $outfile = "$outdirname/"."$file";
open my $output , ">$outfile" || die "Can't open the output file!"
+;
print "file: $file\n";
while ( my $line = <$filename> ) {
$line =~ s/^\s+//;
$line =~ s/ +/ /g;
$line =~ s/\s+$/\n/g;
print $output $line;
}
close ($output);
$variable++;
}
$filename is the name of the file to open, and read from. In your code, "$filename" is not a FILEHANDLE.
In Perl Programming, you need a file-handle in the open function like thus:
open FILEHANDLE,MODE,EXPR Note: that you are not opening, your file named "$filename" to read from. You are just using it in the while loop with readline function as while ( my $line = <$filename> ) {...} which should really be while ( my $line = <FILEHANDLE> ) {...}
So, your code should be something like:
foreach my $filename( @files ){
my $file = "text_000".$variable."."."lab";
my $outfile = "$outdirname/"."$file";
open my $output,'>',$outfile or die "Can't open the output file: $
+!"; ## updated
open my $fh,'<',$filename or die "can't open file: $!"; ## add
+ed
print "file: $file\n";
while ( my $line = <$fh> ) {
$line =~ s/^\s+//;
$line =~ s/ +/ /g;
$line =~ s/\s+$/\n/g;
print $output $line;
}
close $fh or die "can't close file: $!"; ## added
close $output or die "can't close file: $!"; ## updated
$variable++;
}
NOTE: All codes are not tested please.
If you tell me, I'll forget.
If you show me, I'll remember.
if you involve me, I'll understand.
--- Author unknown to me
| [reply] [d/l] [select] |
You need to "open" your input file dummy
| [reply] |
There are two different answers above which point you to this but the essence is - If you are not using brackets you must know operator precedence.
And of course you should also know that 'or' works between statements because each statement evaluates to true or false.
Getting messed up with file open occurs so often that I find it far easier to enforce die on failure. I understand why Perl does this but personally when I open a file, nearly always, I expect to have it open.
| [reply] |
| [reply] |
I'm not sure whether the answer is in the above rather lengthy-looking thread, but it is:
# the die() will never get executed
# because of operator precedence
open my $output , ">$outfile" || die "Can't open the output file!";
# this would work:
open(my $output , ">$outfile") || die "Can't open the output file!";
# and so would this:
open my $output , ">$outfile" or die "Can't open the output file!";
| [reply] [d/l] |