Paul Serikov
Paul Serikov

Reputation: 3111

Most elegant and fastest way to remove all leading zeroes in perl string

I wrote rmlz function for trimming all leading zeroes from string.

# remove all leading zeroes from string
use strict;
use warnings;
use feature 'say';

sub rmlz {
  my ( $str ) = @_;
  if ( $str =~ /^(.[0])/ ) {
    return substr( $str, length($1));
  }
  return $str;
}

say rmlz('0050625'); # must return 50625

Is there most elegant and clear way to rewrite this code ? Or regexp+length+substr is best option ?

Upvotes: 1

Views: 4340

Answers (4)

Milton Earnest Zilmer
Milton Earnest Zilmer

Reputation: 29

$_+=0;

this problem is more easily solved by math than regex

Upvotes: 0

zdim
zdim

Reputation: 66873

Since this seems to be about a number, can reformat it as such (if indeed an integer)

my $num = sprintf "%d", $num_in_str;

or have Perl take care of it by making it treat the string as a number

my $num = 0 + $num_in_str;   # or just:  $num_in_str += 0;

This does the right thing for any kind of number in $num_in_str, and it is incomparably more efficient than sprintf or starting a regex engine. While it may appear tricky it's fine in a sub

sub rmlz { return 0+$_[0] }

where you practically pay only for the function call overhead (still a bit in Perl).

Both of these print warnings if $num_in_str isn't a valid number, what is good in my opinion (unless you need to work with things like 0023a, in which case you want a regex).

Upvotes: 4

ysth
ysth

Reputation: 98388

A simple substitution will remove leading zeros:

$str =~ s/^0+(?=[0-9])//;

This removes as many zeros as possible while still leaving at least one digit. The latter constraint is needed to prevent "0" becoming "".

Upvotes: 9

JGNI
JGNI

Reputation: 4013

Use the substitute operator

$str =~ s/^0+//

Replace the beginning of the string followed by 1 or more 0 with nothing instead of

if ( $str =~ /^(.[0])/ ) {
    return substr( $str, length($1));
}

Upvotes: 1

Related Questions