http://qs321.pair.com?node_id=586739


in reply to Re: Splitting a string to chunks
in thread Splitting a string to chunks

thx for pointing out. what about
'regexpad' => sub { # padding the string my $padding = 8 - length($str%8) if length($str%8); #has to be 8 - m +odulo not modulo, thx johngg $str .= "x" x $padding; # dividing the string in parts of 8 chars my @arr = $str =~ /(........)/g; #remove padding $arr[-1] = substr($arr[-1],-$padding); }
although its a bit slower than the other 2 regex solutions
Rate split_pos grep_split substr_map regexpad regexo re +gex substr_loop unpack split_pos 5841/s -- -64% -70% -75% -76% - +76% -79% -80% grep_split 16129/s 176% -- -17% -30% -33% - +34% -42% -45% substr_map 19531/s 234% 21% -- -15% -19% - +20% -30% -33% regexpad 22936/s 293% 42% 17% -- -5% +-6% -17% -22% regexo 24038/s 312% 49% 23% 5% -- +-1% -13% -18% regex 24272/s 316% 50% 24% 6% 1% + -- -13% -17% substr_loop 27778/s 376% 72% 42% 21% 16% +14% -- -5% unpack 29240/s 401% 81% 50% 27% 22% +20% 5% --
Edit: corrected padding

--
"WHAT CAN THE HARVEST HOPE FOR IF NOT THE CARE OF THE REAPER MAN"
-- Terry Pratchett, "Reaper Man"

Replies are listed 'Best First'.
Re^3: Splitting a string to chunks
by johngg (Canon) on Nov 29, 2006 at 23:25 UTC
    I think your "padding" algorith might be a bit wonky. Given a string of length, say, 19 characters you would arrive at a $padding value of 3, thus padding your $str with three "x"s to end up with a length of 22, not 24 as I think you wanted. This should work (not tested)

    my $padding = 8 - ($str % 8);

    The remove padding part would be something like (again, not tested)

    substr $arr[-1], -$padding, $padding, q{} if $padding;

    Cheers,

    JohnGG

    Update: I must have been half-asleep; where's the length call? Line should be

    my $padding = 8 - (length($str) % 8);

    You can't do modulo on a string :)

    $ perl -le '$str = q{abc}; $pad = $str % 8; print $pad;' 0 $ perl -le '$str = q{abcdefghijkl}; $pad = $str % 8; print $pad;' 0 $