in reply to reading in fixed width

If you truly mean to have overlapping fields, I don't think unpack would work, but substr or a lookahead regex would:

substr: Note that second parameter is 0-based. A warning will be given if the start position is beyond (but not at!) the end of the string; the result will be shorter than the requested length if $in isn't long enough.

$one = substr($in, 23, 15); $two = substr($in, 28, 10);
Beware! If you use substr in an lvalue context, the warning gets promoted to an error:
$ perl -we'sub foo { print $_[0] } eval { foo(substr "abc", 4, 1); 1} +or die "croak: $@"' croak: substr outside of string at -e line 1.
regex: use one (?=) anchored at the beginning per field. The offsets are still 0-based.
$in =~ /^ (?=.{23}(.{15})) # field one (?=.{28}(.{10})) # field two /xs or warn "bad input: $in ";
If columns may be shorter, use .{0,15} and .{0,10} or similar. If a starting column is beyond the end of the string, the regex will fail.

Replies are listed 'Best First'.
Re^2: reading in fixed width
by holli (Abbot) on Feb 27, 2005 at 21:17 UTC
    You can do overlapping fields with unpack.
    my $data = "123"; my @data = unpack "A2X1A2", $data; print "@data";
    This prints
    12 23


    holli, /regexed monk/