user2013387
user2013387

Reputation: 203

Inserting space in result in perl

I have a number like 600000. I want to insert space after every 2 digit. How can I do it? The result should be 60 00 00.

Upvotes: 2

Views: 153

Answers (4)

ikegami
ikegami

Reputation: 386371

If 12345 should become 12 34 5, I recommend

s/..(?!\z)\K/ /sg

The (?!\z) ensures that you don't add a trailing space.


If 12345 should become 1 23 45, I recommend

s/(?!^)(?=(?:..)+(?!.))/ /sg

(?!^) ensures you don't add a leading space.

This isn't very efficient. It might be more efficient to reverse the input, use the first solution, then reverse the output.

Upvotes: 7

AKHolland
AKHolland

Reputation: 4445

Compared a few different methods of doing this. I assumed that you didn't want to modify the original string, otherwise the 100% regex version might have done better.

#!/usr/bin/perl

use strict;
use warnings;

use Benchmark ();

my $x = "1234567890";

Benchmark::cmpthese(1_000_000, {
    unpack   => sub { join(" ", unpack("(A2)*", $x)) },
    regex    => sub { (my $y = $x) =~ s/..(?!\z)\K/ /sg; $y },
    regex514 => sub { $x =~ s/..(?!\z)\K/ /sgr },
    join     => sub { join(" ", $x =~ /..?/sg) },
    });

Seems that using unpack() is the fastest

             Rate     join    regex regex514   unpack
join     221828/s       --     -18%     -26%     -42%
regex    271665/s      22%       --     -10%     -29%
regex514 300933/s      36%      11%       --     -22%
unpack   383877/s      73%      41%      28%       --

Upvotes: 5

Kenosis
Kenosis

Reputation: 6204

Here's another option:

use strict;
use warnings;

my $number = 600000;
my $spacedNum = join ' ', $number =~ /..?/g;
print $spacedNum;

Output:

60 00 00

Upvotes: 2

AgileTillIDie
AgileTillIDie

Reputation: 469

Try this:

$number = '600000';
$number =~ s/(\d{2})(?!$)/$1 /g;
print $number;

(\d{2}) means 'two numerical digits'. (?!$) means 'as long as the end of the string isn't immediately afterwards', as there's no need for a space after the number.

Upvotes: 3

Related Questions