linux - Read and Write Operation in perl script -
i newbie perl script.
i want read , write operation on file. open file in read , write mode (+<), , write file. now, want read file whatever have written previously. below code:
#!/usr/bin/perl `touch file.txt`; #create file opening file in +< mode open (outfile, "+<file.txt") or die "can't open file : $!"; print outfile "hello, welcome file handling operations in perl\n"; #write file $line = <outfile>; #read file print "$line\n"; #display read contents. when displaying read contents it's showing blank line. file "file.txt" has data
hello, welcome file handling operations in perl why not able read contents. whether code wrong or missing something.
the problem filehandle position located after line have written. use seek function move "cursor" top before reading again.
an example, comments:
#!/usr/bin/env perl # use recommended safeguards use strict; use warnings; $filename = 'file.txt'; `touch $filename`; # use indirect filehandle, , 3 argument form of open open (my $handle, "+<", $filename) or die "can't open file $filename : $!"; # btw job on checking open sucess! print $handle "hello, welcome file handling operations in perl\n"; # seek top of file seek $handle, 0, 0; $line = <$handle>; print "$line\n"; if doing lots of reading , writing may want try (and not suggests it) using tie::file lets treat file array; line access line number (newline written automatically).
#!/usr/bin/env perl # use recommended safeguards use strict; use warnings; use tie::file; $filename = 'file.txt'; tie @file, 'tie::file', $filename or die "can't open/tie file $filename : $!"; # note file not emptied if exists push @file, "hello, welcome file handling operations in perl"; push @file, "some more stuff"; print "$file[0]\n";
Comments
Post a Comment