use strict; #12345678901234567890123 my $str= "This That Other Next Last "; my $str2="One Fine Morning in May"; my $str3="Some format happened"; #my $fmt= [qw(6 6 7 4)]; # Lengths of each piece my $fmt = getLengths($str); my ($count,$blanklen,@lengths); #print " Length = $_\n" for @{getLengths($str)}; for ($str, $str2, $str3){ print "----Str=[$_] Fmt=@$fmt\n"; print " [$_]\n" for getPiecesByFixedLength($_, $fmt); print "--Last--\n"; } # ---------------------------------------------------------------------------- # Subroutine: getPiecesByFixedLength - given a string, delimiter, and format return an arrray # ---------------------------------------------------------------------------- sub getPiecesByFixedLength { my $OriginalStr = shift || die 'getPiecesByFixedLength: need a string'; my $format = shift || die 'getPiecesByFixedLength: need a format'; ref $format eq 'ARRAY' or die "Second param Must be array ref\n"; my @out = (); foreach ( @$format ) { s/\D//g; # - save only digits my $ThisPiece = substr($OriginalStr,0,$_); $ThisPiece =~ s/^\s+//; $ThisPiece =~ s/\s+$//; push @out, $ThisPiece; substr($OriginalStr,0,$_) = ''; } return @out; } # ---------------------------------------------------------------------------- sub getLengths{ # Return a ref to an array containing Lengths of pieces of the string.. my $OriginalStr=shift || die "getLengths needs string param\n"; my ($count, @ret); foreach(split /(\s+)/,$OriginalStr){ m/^\s+$/ and $ret[$count - 1]+= length($_) , next; $ret[$count] = length($_); #print "Got Piece $count [$_] Len " . length($_) . "\n"; $count++; } wantarray? return @ret : return \@ret; } # ----------------------------------------------------------------------------