Perl Open Howto

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.

Subroutine to open a file for reading, and read and return its contents.

Solution

    sub read_file
    {
        my ( $f ) = @_;
        open F, "< $f" or die "Can't open $f : $!";
        my @f = <F>;
        close F;
        return wantarray ? @f : \@f;
    }

Subroutine to open a file for writing and write into it.

Solution

    sub write_file
    {
        my ( $f, @data ) = @_;
        @data = () unless @data;
        open F, "> $f" or die "Can't open $f : $!";
        print F @data;
        close F;
    }

Open a file and print its contents.

Solution

    open( FILE, "< $filename" ) or die "Can't open $filename : $!";
    while( <FILE> ) {
        print;
    }
    close FILE;

Read from one file and write its contents into another 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;

Ignore comments while reading a data file.

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
    }


AUTHOR

Alex BATKO <abatko AT cs.mcgill.ca>

Thanks to all those who have written with suggestions and comments.


DONATE

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!


SEE ALSO

http://www.cs.mcgill.ca/~abatko/computers/programming/perl/howto/

http://alex.exitloop.ca/abatko/computers/programming/perl/howto/