in reply to regular expressions query

Like most things in Perl, there are usually many different ways to accomplish the same thing. Others have given good suggestions using regular expressions, split, etc. But I don't think anyone has mentioned unpack yet.

If your situation involves fixed length records where each field occupies the same columns on each record, then unpack will work for you.

The Perl Cookbook p.297 has recipe 8.15 titled "Reading Fixed-Length Records" which describes using unpack:

# $RECORDSIZE is the length of a record, in bytes. # $TEMPLATE is teh unpack template for the record # FILE is the file to read from # @FIELDS is an array, one element per field until ( eof(FILE) ) { read(FILE, $record, $RECORDSIZE) == $RECORDSIZE or die "short read\n"; @FIELDS = unpack($TEMPLATE, $record); }
Now to relate that to your example (I'm on Windows XP):
#!perl -w use strict; my $record = " none lt2dpmnt"; print "\$record = [$record]\n"; my @FIELDS = unpack('a9a4a10a8', $record); foreach (@FIELDS) { print "field=[$_]\n"; }
Produces this output:
C:\DOCUME~1\hmerrill.000\TEST_P~1>test_unpack.pl $record = [ none lt2dpmnt] field=[ ] field=[none] field=[ ] field=[lt2dpmnt]
Again, this only works if you know that every record is the same length, and each field in the record occupies the same columns. "perldoc -f pack" and "perldoc -f unpack" for more information.

HTH.

Replies are listed 'Best First'.
Re^2: regular expressions query
by injunjoel (Priest) on Jul 02, 2004 at 18:06 UTC
    Greetings all,
    Just an FYI you can use an 'x' in your unpack template to remove the spaces ('x'='A null byte.'), that is unless you want the spaces.
    so
    my @FIELDS = unpack('a9a4a10a8', $record);

    becomes
    my @FIELDS = unpack('x9a4x10a8', $record);

    Given your example code above the output would be:
    $record = [ none lt2dpmnt] field=[none] field=[lt2dpmnt]


    -injunjoel
    "I do not feel obliged to believe that the same God who endowed us with sense, reason and intellect has intended us to forego their use." -Galileo