Search code examples
regexstringperlsubstring

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 ?


Solution

  • 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 "".