How can I remove all the leading zeroes but leave a final zero if the value only contains zeroes?
for example:
my $number = \"0000\";
Just add 0 to the string so that it's implicitly converted to a number:
my $var = '0000035600000';
$var += 0;
This should work:
$number =~ s/^0*(\d+)$/$1/;
0 -> 0
0000 -> 0
0001 -> 1
Edit: turns out that's just a bit too complicated. This should also work:
$number =~ s/0*(\d+)/$1/;
but I'm not sure which is better, depends on the use case.
Do check out the answer from Oesor: it's pretty sweet too, no regex involved.
If your $number
is an integer, another way is to use printf:
for my $number (qw(005 05 5 000 0 500)) {
printf "%d\n", $number;
}
__END__
5
5
5
0
0
500
Edit: As ysth points out, it works for all integers, not just positive integers as I originally stated.
Well if you want to replace all by one just change to s/^0+/0/
?
However, this will replace all leading 0's by one 0 so if you have leading zeros before numbers you will need Mats construct.
$number =~ s/^0+(?=\d)//;
The positive lookahead ensures there's at least one digit left, and using +
instead of *
means the substitution is skipped if there are no leading zeroes.
If you're trying to normalize groups of numbers in a single string, just use \b
instead of ^
, and do a global substitution:
my $data = "0225 0000 030";
$data =~ s/\b0+(?=\d)//g;
Some answers are implicitly assuming there are only digits present or that $number
is in fact a number. If this is not the case:
s/^0+(?=.)//s
Or even:
substr($number,0,-1) =~ s/^0+//s