in reply to inserting in different places in a file

This smells like the same homework as This node and This one. Please look for responses in those.

"Experience is a wonderful thing. It enables you to recognize a mistake when you make it again."
  • Comment on Re: inserting in different places in a file

Replies are listed 'Best First'.
Re: Re: inserting in different places in a file
by Anonymous Monk on Feb 27, 2004 at 22:24 UTC
    what if it smells like homework , I am asking for ideas only :) , I don't need a solution . thanks anyway
      OK - here is some code I wrote (part of it shamelessly plagerized) because I could not find a module to satisfactorily parse your kind of data. This sould probably be retro-fitted into Text::FixedLength.

      If you can figure out how to apply the 2 subroutines to your homework, power to you!:

      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 strin +g'; my $format = shift || die 'getPiecesByFixedLength: need a forma +t'; 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 strin +g.. 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; } # -------------------------------------------------------------------- +--------

      "Experience is a wonderful thing. It enables you to recognize a mistake when you make it again."
        -- Let him learn like everyone else or he will be just another developer in the market that can't figure out anything for himself.


        -Waswas
        thanks , I will try :)