raybies has asked for the wisdom of the Perl Monks concerning the following question:

I've a six character string I'd like to split into three character pairs. I just keep thinking it should be easier to split the string in pairs, than my solution. The closest I can get is this:

 $var1 = $1 and $var2 = $2 and $var3 = $3 if /(.{2})(.{2})(.{2})/;

Can anyone think of a more elegant and perly way to do this? Just curious.

Replies are listed 'Best First'.
Re: split fixed string into character pairs
by Anonyrnous Monk (Hermit) on Dec 09, 2010 at 15:14 UTC

    or with unpack:

    my $s = "aabbcc"; my ($var1, $var2, $var3) = unpack "(A2)*", $s; say for $var1, $var2, $var3; __END__ aa bb cc
Re: split fixed string into character pairs
by JavaFan (Canon) on Dec 09, 2010 at 15:15 UTC
Re: split fixed string into character pairs
by kennethk (Abbot) on Dec 09, 2010 at 15:11 UTC
    In list context, a regular expression will return the elements of its capture buffers. This means

    my ($var1, $var2, $var3) = /(.{2})(.{2})(.{2})/;

    or even:

    my (@array) = /(.{2})(.{2})(.{2})/;

    will do what you need and avoids a bunch of potential scoping issues. See Extracting matches in perlretut.

Re: split fixed string into character pairs
by Ratazong (Monsignor) on Dec 09, 2010 at 15:23 UTC
    The following solution is not very scaleable, not really perlish (other than being an example for TIMOTOWTDI), but at least easily understable ...:
    my $str = "abcdef"; my $v1 = substr $str, 0,2; my $v2 = substr $str, 2,2; my $v3 = substr $str, 4,2;
Re: split fixed string into character pairs
by raybies (Chaplain) on Dec 09, 2010 at 15:46 UTC
    Thanks for all the great responses. Some pretty obvious ones. :) I should not have stayed up so late last night... JavaFan gets extra kudos for least number of characters. :)

      In perl that is by no means a guarantee to also be the fastest code :)

      If your dataset is large/huge, you'd notice that the unpack solution posted by an Anonymous Monk was way faster than all the others. And once you are used to that, it will be much easier to extend and maintain than regular expressions.


      Enjoy, Have FUN! H.Merijn