On Tue, 28 Jan 2003, Phil Pereira wrote:

> Is there an easy way to split "123456" into "12-34-56"?
>
> I've been splitting with a basic // into an array, and then printing 2
> array elements at a time, sorta like:  $array[0] . $array[1]

Golf solutions aside (where people try and solve it in the fewest possible
keystrokes) lets see what you're trying to do.

Ideally you'd want an array that looks like

 @array = ( "12", "34", "56" );

As then you can simply use the join operator to join this list together to
get the output you want

 $output = join "-", @array;

Of course, there's more than one way to solve it. One way to solve this
problem is to use a loop to take the first two chars from the string each
time you run over the loop.

  my @array;
  while (length($input))
  {
    # take the first two chars from the string
    # each loop and replace it with the empty string
    my $twochar = substr $input, 0, 2, "";

    # add it to the array
    push @array, $twochar;
  }

This will of course destroy your input string, so you might want to copy
it first.  See "perldoc -f substr" for more info.

Another way is to use a loop with a regular expression to match two chars
with the funky 'g' option to tell it to match each loop starting from
where it left off at the end of the previous loop (so it moves slowly
along the input string).

  my @array;
  while ($input =~ /(..)/g)  # while we match.
  {
    # store the thing in the ( ) in the regex in @array.
    push @array, $1;
  }

This regular expression uses the "." pattern, meaning 'match any char' and
uses the braces ( ) so that the .. is placed in each loop $1.  See the
perlrequick and perlregex documentation for more info.

The last one I can think of (though there will be many more) is to use the
unpack operator.  This is somewhat like a regular expression where you
define a "template" that the string will be broken up into.

  my @array = unpack "(A2)*", $input;

This uses a simple template.  'A' means an ASCII char, '2' means two of
them, and then we use the '( )*' to indicate that it should repeat that
pattern to consume the whole input.  See perldoc -f unpack and perldoc -f
pack for more info.

Mark.

-- 
#!/usr/bin/perl -T
use strict;
use warnings;
print q{Mark Fowler, [EMAIL PROTECTED], http://twoshortplanks.com/};

Reply via email to