This how-to comes with no guaratees other than the fact that these code segments were copy/pasted from code that I wrote and ran successfully.
Solution
sub read_file { my ( $f ) = @_; open F, "< $f" or die "Can't open $f : $!"; my @f = <F>; close F; return wantarray ? @f : \@f; }
Solution
sub write_file { my ( $f, @data ) = @_; @data = () unless @data; open F, "> $f" or die "Can't open $f : $!"; print F @data; close F; }
Solution
open( FILE, "< $filename" ) or die "Can't open $filename : $!";
while( <FILE> ) { print; }
close FILE;
Solution
my $infile = 'foo.txt'; my $outfile = 'bar.txt';
open IN, "< $infile" or die "Can't open $infile : $!"; open OUT, "> $outfile" or die "Can't open $outfile : $!"; print OUT <IN>; close IN; close OUT;
Read the file content using a while
loop. For each line read,
ignore the comments, and skip blank lines. Push all other lines of data into
an array named lines. The chomp is done after the comment and blank
line portion inorder to avoid unnecessary processing time.
Solution
while( <FILE> ) {
s/#.*//; # ignore comments by erasing them next if /^(\s)*$/; # skip blank lines
chomp; # remove trailing newline characters
push @lines, $_; # push the data line onto the array }
Example
sub read_file { my( $filename ) = shift; my @lines;
open( FILE, "< $filename" ) or die "Can't open $filename : $!";
while( <FILE> ) {
s/#.*//; # ignore comments by erasing them next if /^(\s)*$/; # skip blank lines
chomp; # remove trailing newline characters
push @lines, $_; # push the data line onto the array }
close FILE;
return \@lines; # reference }
Alex BATKO <abatko AT cs.mcgill.ca>
Thanks to all those who have written with suggestions and comments.
Hi! If this document helped you figure out something you were stuck on; if it saved you time; if it relieved some frustration or anxiety... please consider donating. Thank you kindly!
http://www.cs.mcgill.ca/~abatko/computers/programming/perl/howto/
http://alex.exitloop.ca/abatko/computers/programming/perl/howto/