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 ...

Get Learning Perl, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.