kinnerc has asked for the wisdom of the Perl Monks concerning the following question:

Folks:

I can't stand when I THINK things should work, and then not only don't they, but they give absolutely no indication at to why they are not doing what they should be doing.

What I want to do is input a real number and then split it between the left part of the decimal point and the right part of the decimal point. Now its my understanding that there is no difference in Perl between numbers and strings so I can't for the life of me understand why this doesn't work.

Code:

$hjd = 25445.3382; @fields = split /./, $hjd; print "$fields[1]\n"; # I expect to get '3382' I get a newline print "$fields[0]\n"; # I expect to get '25445' I get a newline

There may be better ways to do what I want to do. I understand that. But I have no idea why what I have coded above does not work.

Very frustrating, unfortunately.

Doc Kinne

Replies are listed 'Best First'.
Re: Question about Numbers, Strings & SPLIT
by erroneousBollock (Curate) on Nov 29, 2007 at 04:38 UTC
    You need to escape '.' in the regular expression like this:

      split /\./

    '.' in a regular expression matches any single character, rather than the period character.

    Please have a look through perlre.

    Personally, I like to do:

    my ($whole,$fract) = ($hjd =~ /(\d+)(\.\d+)?/);
    If $fract isn't defined, it'll be evaluated as zero when used numerically.

    -David

      David:

      Bingo! You're a sanity saver! "." is a metacharacter! Of course! One blasted simple thing!

      THANK YOU!!!

      Doc Kinne