O'Reilly logo

Learning Perl, Second Edition by Randal L. Schwartz, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

A.9. Chapter 10

  1. Here's one way to do it:

    print "What file? ";
    chomp($filename = <STDIN>);
    open(THATFILE, "$filename") ||
        die "cannot open $filename: $!";
    while (<THATFILE>) {
        print "$filename: $_"; # presume $_ ends in \n
    }

    The first two lines prompt for a filename, which is then opened with the filehandle THATFILE. The contents of the file are read using the filehandle and printed to STDOUT.

  2. Here's one way to do it:

    print "Input file name: ";
    chomp($infilename = <STDIN>);
    print "Output file name: ";
    chomp($outfilename = <STDIN>);
    print "Search string: ";
    chomp($search = <STDIN>);
    print "Replacement string: ";
    chomp($replace = <STDIN>);
    open(IN,$infilename) ||
        die "cannot open $infilename for reading: $!";
    ## optional test for overwrite...
    die "will not overwrite $outfilename" if -e $outfilename;
    open(OUT,">$outfilename") ||
        die "cannot create $outfilename: $!";
    while (<IN>) {    # read a line from file IN into $_
        s/$search/$replace/g; # change the lines
        print OUT $_; # print that line to file OUT
    }
    close(IN);
    close(OUT);

    This program is based on the file-copying program presented earlier in the chapter. New features here include prompting for the strings and the substitute command in the middle of the while loop, as well as the test for overwriting a file.

    Note that backreferences in the regular expression do work, but referencing memory in the replacement string does not.

  3. Here's one way to do it:

    while (<>) { chomp; # eliminate the newline print "$_ is readable\n" if -r; print "$_ is ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required