Search code examples
stringperlnumericdata-conversion

Numeric to String conversion in Perl


According to my knowledge when ever a string like

$a="120.43sunil"+5;    

it will give a result like

$a=125.43     

since string is not a number the "sunil" part will be omitted. what if we get some thing like

$a="12fred34"*" 3"   

will the string be converted to 1234 or 12034 ? im kind a new to perl programming.


Solution

  • If you turn on strict and warnings - like you really should - it will warn you.

    Which is good, because it's a bad idea.

    If you try your code, you'll see your second example gives:

    my $val="12fred34"*" 3"   ;
    print $val;
    

    Gives:

    Argument "12fred34" isn't numeric in multiplication (*)
    36
    

    perl is "finding" the 12, and using that, discarding the rest.

    Your first example by the way - also warns:

    Argument "120.43sunil" isn't numeric in addition (+)
    

    But really - this is just a bad idea.

    perl implicitly converts string to number when it can, but will warn if it can't. That's because in your second case, it's ambiguous. Should the text be zero? Ignored? Is this even one number, or is it two?

    If you really need to convert to a number a part of a string, you should really parse the string first, and extract the values you want. That can be as simple as

    $val =~ s/\D//g; 
    

    But it might be:

    @vals = $str =~ m/(\d+)/g; 
    

    And if you really want to do fruity things with numbers and strings, look at dualvar*:

    #!/usr/bin/env perl
    use strict;
    use warnings;
    
    use Scalar::Util qw ( dualvar ); 
    
    my $val = dualvar ( 120.43, "sunil" );
    
    print $val,"\n";
    print $val + 0; #force numeric context;
    

    And whilst we're at it - don't use $a or $b - they are variables with a specific use in perl - sorting. You shouldn't really use single letter variables anyway, it's a bad coding habit.

    * I wouldn't actually recommend messing around with dualvars - they're really cool, but can make some really horrible code if used badly, which is what'll probably happen if you're "kind a new to perl programming"