in reply to Problem With Split

You can combine look behind and look ahead in the regex of the split:

#!/usr/local/bin/perl -w use strict; my $number = '00120034'; # split at the position that has 4 digits # behind and 4 digits ahead my ($n1, $n2) = split /(?<=\d{4})(?=\d{4})/, $number; print "$n1, $n2\n"; # strip leading 0's ($n1, $n2) = map { int $_ } ($n1, $n2); print "$n1, $n2\n";

And the output is as expected...
0012, 0034 12, 34


This technique is very useful. For example, you could comma'fy a floating point number with look ahead and look behind in one go, sort of... :-)
{ local $_ = $amount; /\./ ? s/(?<=\d)(?=(\d{3})+(?:\.))/,/g : s/(?<=\d)(?=(\d{3})+(?!\d)) +/,/g; $amount = $_; }

Replies are listed 'Best First'.
Re^2: Problem With Split
by Roy Johnson (Monsignor) on Jun 16, 2004 at 18:59 UTC
    Maybe you should submit that as a Q&A answer.

    Here's another stab:

    s{(?<!\d|\.)(\d+)} {my $n=$1; $n=~s/(?<=\d)(?=(?:\d{3})+$)/,/g; $n }e;

    We're not really tightening our belts, it just feels that way because we're getting fatter.
Re^2: Problem With Split
by revdiablo (Prior) on Jun 16, 2004 at 18:34 UTC
    This technique is very useful

    Lookahead and lookbehind are both very useful indeed, but I think your example is better solved with a sexeger:

    $amount = reverse $amount; $amount =~ s/(\d{3})/$1,/g; $amount = reverse $amount;

    Update: oops, I guess my example doesn't commafy a floating-point number, now does it? Oh well. At least maybe someone will learn about sexegers who didn't know about them. 8^)