in reply to Re^3: Breaking up a string?
in thread Breaking up a string?

Because I then wanted to get the next 6 chars, then the 6 after that, until the end of the string (length is a multiple of 6).

Replies are listed 'Best First'.
Re^5: Breaking up a string?
by stiller (Friar) on Feb 19, 2008 at 15:12 UTC
    I'm very unsure about what you really want, but this capture my understanding of what you ask for:
    use strict; use warnings; my $input = '1234562234563334564444565555566789'; my @sets_of_six; while (length $input > 6){ my $front = substr($input, 0, 6); $input = substr($input, 6); push @sets_of_six, $front; } push @sets_of_six, $input if length $input > 0; use Data::Dumper; print Dumper( @sets_of_six );
    Now, that is a rather naive solution, it's not very effective, nor is it very perl'ish, but I think you might understand what is happening.
    Is it faintly aproaching your question?
    hth
      while (length $input > 6){ my $front = substr($input, 0, 6); $input = substr($input, 6); push @sets_of_six, $front; }
      This can be done slightly more compactly by having the initial substr remove the leading characters as it retrieves them:
      while (length $input > 6){ my $front = substr($input, 0, 6, ''); push @sets_of_six, $front; }
      (Or even get rid of $front entirely with
      while (length $input > 6){ push @sets_of_six, substr($input, 0, 6, ''); }
      if you don't think that's becoming too unreadable.)
        I think you show the progression from extremely simple to comprehend but overly verbose, gradually into a much more acceptable solution in a very fine way that should be easy to follow and learn from.
        I think that your progression ends at a nice place too, unless one work in a shop where perl is a primary language.
        My preference is unpack, as BrowserUk demonstrates,
        cheers