View Single Post
Old 10-21-2002, 07:06 PM   #5 (permalink)
gwartheg
Registered User
 
gwartheg's Avatar
 
Join Date: Aug 2002
Location: Boston, MA
Posts: 8
gwartheg is on a distinguished road
Send a message via ICQ to gwartheg
Re: Re: Working with Text Files

No, I don't mind at all. Shame on me for throwing up code without explaining it :o
Code:
open (IN, "file") or die "Can't read file: $!\n";  # 1
while ( <IN>) {                                   # 2
    chomp;                                         # 3
    my @fields = split;                            # 4
    if ($fields[0] =~ /PATTERN/) {                 # 5
        # do something
    }
}
close(IN);                                         # 6
# 1 - Here I'm using the "open" function to attach the file handle IN to the external file "file". If it's unsuccessful, the script dies and gives an error message.
# 2 - I'm using the diamond operator (<>) with the file handle to read each line in the file. Used with "while" it means, "execute this block as long as there is a line to be read from IN". Each line gets set to the variable $_ in turn.
# 3 - Remove any trailing newline.
# 4 - Each line gets split up into a list (split uses the pattern /\s+/ to split by default). I regularly use files with tab-delimited fields, so this is convenient for me.
# 5 - This says, "execute this block if the first item in the list looks like this pattern".
# 6 - This just explicitly closes the file I was looking in.
Code:
my @lines = <IN>;                      # 1
my @stuff = grep { /PATTERN/ } @lines; # 2
print @stuff;                          # 3
You could use these lines in place of the while loop, if you wanted a list of entire lines for which a given expression is true (usually a pattern match).
# 1 - Read all lines from IN into a list, where the first element is the first line, and so on.
# 2 - This says, "if an element in the list @lines contains PATTERN, add it to the list @stuff". It's just quicker than writing a for loop with a conditional and all that.
# 3 - This just spits out whatever is in @stuff. Notice that the input wasn't chomped, and that the @stuff isn't surrounded with quotes. I'm assuming that the input file has one record on each line, and I don't want the print function to put extra spaces between the list elements.

I know there are some file access tutorials online, but I've found that they're generally limited in scope and can't compete with a good book at hand. Oh, and coderforums.net is another good forum to visit. There are plenty of people there that know a ton more about Perl than me
gwartheg is offline   Reply With Quote