P
pembed2003
Hi all,
I am trying to come up with a regex to format number like:
1234
-1234
1234567
to:
1,234
-1,234
1,234,567
The numbers will always be interger. So far, I have the following:
#1:
while(<>){
chomp;
$_ = reverse split //;
s/(\d{3})\B/$1,/g;
$_ = reverse split //;
print "$_\n";
}
#2:
while(<>){
chomp;
my $n = $_ =~ s/^-// ? '-' : '';
$_ = 'x' . $_ while(length($_) % 3);
s/(.{3})\B/$1,/g;
s/^[x,]+//;
print "$n$_\n";
}
#3:
while(<>){
chomp;
my $n = '';
while(s/\B(\d{3})$//g){
$n = ",$1" . $n;
}
$n = $_ . $n if length;
print "$n\n";
}
All three methods seems to be a bit too "long", is there a better way?
I am trying to do this as a way for me to learn regex so I would like
not to use a module if possible. Thanks!
I am trying to come up with a regex to format number like:
1234
-1234
1234567
to:
1,234
-1,234
1,234,567
The numbers will always be interger. So far, I have the following:
#1:
while(<>){
chomp;
$_ = reverse split //;
s/(\d{3})\B/$1,/g;
$_ = reverse split //;
print "$_\n";
}
#2:
while(<>){
chomp;
my $n = $_ =~ s/^-// ? '-' : '';
$_ = 'x' . $_ while(length($_) % 3);
s/(.{3})\B/$1,/g;
s/^[x,]+//;
print "$n$_\n";
}
#3:
while(<>){
chomp;
my $n = '';
while(s/\B(\d{3})$//g){
$n = ",$1" . $n;
}
$n = $_ . $n if length;
print "$n\n";
}
All three methods seems to be a bit too "long", is there a better way?
I am trying to do this as a way for me to learn regex so I would like
not to use a module if possible. Thanks!