www.perl.com
Perl Programming
Reading from Files
  • Reading from files
    • Easy to loop over entire file
    • Loops will assign to $_ by default
    • Be sure that the file is open for reading first

        open CUSTOMERS, "< mailing_list" or die "Can't open input file: $!";

        while (my $line = <CUSTOMERS>) {
          my @fields = split(":", $line);      # Fields separated by colons 
          print "$fields[1] $fields[0]\n";     # Display selected fields
          print "$fields[3], $fields[4]\n";
          print "$fields[5], $fields[6]  $fields[7]\n";
        }

        print while <>;                        # cat
        print STDOUT $_ while ($_ = <STDIN>);  # same, but more verbose
      

        Last name:First name:Age:Address:Apartment:City:State:ZIP
        Smith:Al:18:123 Apple St.:Apt. #1:Cambridge:MA:02139

        Al Smith
        123 Apple St., Apt. #1
        Cambridge, MA  02139
      
Previous http://stuff.mit.edu/iap/perl/