Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have a directory with umpteen files in it. (One file for each day of the year going back to 1997)
Each file has umpteen lines in it.
Each line has a | delimited list in it. (The pipe was the one character that didn't seem to be used in the files)

I need to be able to open the files (no problem),
process each line (no problem)
and assign a variable to each bit of info within the | delimited list (problem).
These vars will then be used to populate a database.

I was thinking the best way would be to stuff each line into an array then use that to create the vars. After going through the array info in my Perl books and the Q&A on arrays on this site, now I'm not so sure.

If an array is the way to go, I have been unable to separate the info in each line at the |.
Split doesn't do it since that only seems to separate on whitespace and I *definitely* don't want to do that.

I also checked out the 'files' and 'strings' section with no enlightenment.

I know this *has* to be a simple thing to do but I just can't seem to do it. Can any of you point me in the right direction? I would definitely appreciate the help.

Thanks,
Susan

Replies are listed 'Best First'.
Re: array substr or what?
by mifflin (Curate) on Apr 06, 2005 at 00:07 UTC
    A '|' or pipe is an 'or' in a regex. Escape it in your split.
    erickn@isfe:/home/erickn> cat x use Data::Dumper; $record = 'one|two|three|4|5|six'; print "$record\n"; @record = split /\|/, $record; print Dumper \@record;
    erickn@isfe:/home/erickn> perl x one|two|three|4|5|six $VAR1 = [ 'one', 'two', 'three', '4', '5', 'six' ];
      Oh Man!
      I thought I *had* escaped it in one of my many trials (and errors).

      That did the trick. THANK YOU!

      PerlMonks Rule!

      Susan

Re: array substr or what?
by tlm (Prior) on Apr 06, 2005 at 00:11 UTC

    split (q.v.) is more versatile than you realize. In particular,

    my @fields = split /\|/, $record;
    will put |-delimited fields in @fields. Note that you need to escape the | because it is a regexp character.

    the lowliest monk

Re: array substr or what?
by dynamo (Chaplain) on Apr 06, 2005 at 00:14 UTC
    I'm going to guess you are using the 0 argument form of split, which splits on whitespace. Instead of
    foreach (@lines) { @results = split; # splits on whitespace ... # do stuff with results }
    use
    foreach (@lines) { @results = split /\|/; # splits on pipe char ... # do stuff with results }
    Perhaps you tried split /|/ and had trouble because you didn't backslash the |, which is a special character in regex's ----- 'perldoc -f split' will explain in more detail.