in reply to Doing multiple search and replace operations on a string

You could use a has, something like:
my %exponent = ( T => 12, G => 9 , M => 6 , k => 3 , p => -12, n => -9, u => -6, m => -3, ); s/\d(\w)\s/exists $exponent{$1} ? 'e' . $exponent{$1} : '' /ge;

Replies are listed 'Best First'.
Re^2: Doing multiple search and replace operations on a string
by johngg (Canon) on Feb 20, 2014 at 23:06 UTC

    The (\w) will match and capture a digit which doesn't exist in the hash so will be lost in the substitution. Without a look-behind you will also consume and lose the digit before. Better I think to use a character class along with the look-behind.

    $ perl -E ' $val = q{2.73M}; %exp = ( M => 6 ); $val =~ s/\d(\w)/exists $exp{ $1 } ? q{e} . $exp{ $1 } : q{} /e; say $val;' 2.M $ perl -E ' $val = q{2.73M}; %exp = ( M => 6 ); $val =~ s/(?<=\d)(\w)/exists $exp{ $1 } ? q{e} . $exp{ $1 } : q{} /e; say $val;' 2.7M $ perl -E ' $val = q{2.73M}; %exp = ( M => 6 ); $val =~ s/(?<=\d)([TGMkmunp])/exists $exp{ $1 } ? q{e} . $exp{ $1 } : +q{} /e; say $val;' 2.73e6 ~ $

    I hope this is of interest.

    Cheers,

    JohnGG

      Thanks for the suggestion. I will try this out.