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.


In reply to Re: regular expressions query by hmerrill
in thread regular expressions query by apocalyptica

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.