[ale] Simple Perl Question

Greg Sabino Mullane greg at turnstep.com
Mon Feb 25 12:28:58 EST 2002



-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1


I have to make a few comments here. First and foremost, always check 
the results of your function/system calls, regardless of the language. 
In this case, the 'open' line should read:

open(INFO, $ifile) or die "Could not open $ifile: $!\n";


Here's a quick version, with comments:


#!/usr/bin/perl

use strict;

my $ifile = shift or die "Usage: $0 <inputfile>\n";

open(INFO, "$ifile") or die qq{Could not open "$ifile": $!\n};

<INFO>; ## This skips the first line by basically reading in one line 
        ## but failing to do anything with the information returned

while(<INFO>) { ## Starting from line number 2, put each line into $_

  next if /^#/; ## Allow commented lines in the input file
                ## We are searching through $_

  last if /^##END/; ## Just a nice touch, allows you to put whatever 
                    ## you want after the last record

  chomp; ## Remove any newlines so they don't become part of the final field
         ## Note that we don't do this until after the 2 checks above

  my @fields = split(m#\|#, $_, 10); ## We specify a limit of 10 records: no 
                                     ## need to go past the last field we want


  ## Quick sanity check: make sure we have at least 10 fields for this line
  my $numfields = @fields;
  if ($numfields != 10) {
    die "Line $. had $numfields field(s)!\n";
  }

  ## Output the data by using an array slice and a join
  print "The fields were: ";
  print join ", ", @fields[0,4,6,9];
  print "\n";
}

This is not necessarily the way I would write it :) but should be enough 
to get you started.

Greg Sabino Mullane  greg at turnstep.com
PGP Key: 0x14964AC8 200202251225

-----BEGIN PGP SIGNATURE-----
Comment: http://www.turnstep.com/pgp.html

iD8DBQE8enPwvJuQZxSWSsgRAmBRAJ9H3MTyEo4ZMx3bZUyj8hYC1+Cr+wCgqNNH
SZ5CHbdw+KcHnt+6fulWamg=
=EAKV
-----END PGP SIGNATURE-----



---
This message has been sent through the ALE general discussion list.
See http://www.ale.org/mailing-lists.shtml for more info. Problems should be 
sent to listmaster at ale dot org.






More information about the Ale mailing list