Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

changing a string to a numeric variable

by NovMonk (Chaplain)
on Mar 18, 2004 at 21:43 UTC ( #337818=perlquestion: print w/replies, xml ) Need Help??
NovMonk has asked for the wisdom of the Perl Monks concerning the following question:

Greetings, Monks,

Suppose I have a line with both text and numbers in it. Maybe it looks like this:

word 15 word word 20

If I split the line this way:

($a,$b,$c,$d,$e) = split

I find I can use $b and $e as numbers-- do math on them and stuff.


I have a slightly messier line. Instead of 15 I have 15,000 and instead of 20, it's 20,000. I assign it as an array thus:

@line = split

And now, though $line[1] and $line[4] print out as 15,000 and 20,000, when I try to do any math on them I get an error, that 15,000 or 20,000 isn't a numeric in line whatever.

The question I was going to ask is-- is this something to do with assigning this as an array instead of scalars, but I just stumbled across that answer. I see it's the commas in the variables in the second case causing the problem.

So, new question-- how can I best manipulate $line[1] etc to get rid of the comma? I don't want to change the line I'm splitting because I'm using it later and the comma needs to be there then. I'm having trouble knowing how to think about the string once it's been assigned to a variable. Or, whether I'm even thinking about this the right way at all. ;)

ps this isn't homework. I'm teaching myself trying to solve some simple problems at work, and until I crashed into this I was doing pretty well. We all gotta start somewhere.



Replies are listed 'Best First'.
Re: changing a string to a numeric variable
by kvale (Monsignor) on Mar 18, 2004 at 22:05 UTC
    Commas are not valid characters in numbers. You could replace them with underscores (which are valid in perl), but you dont want to change the format. Here is how to compute with them:
    use warnings; use strict; my $line = "word 15,000 word word 20,000"; my @line = split /\s+/, $line; my $sum; foreach my $word (@line) { next unless $word =~ /^[\d,.+-]+$/; # crappy number detector $word =~ s/,//g; $sum += $word; } print "$sum\n";


Re: changing a string to a numeric variable
by b10m (Vicar) on Mar 18, 2004 at 21:52 UTC

    There are probably nicer ways to solve this, but this seems to work ;)

    $a = "word 15,000 word word 20,000"; @b = split " ", $a; $b[1] =~ s/,//g; $b[4] =~ s/,//g; print $b[1] + $b[4]."\n";

    This will result in "35000"


    Update: It'd of course be nicer (even in my messy example) to use a sub routine for this, which returns the commaless values ...


    All code is usually tested, but rarely trusted.
Re: changing a string to a numeric variable
by pbeckingham (Parson) on Mar 18, 2004 at 22:19 UTC

    The following splits the line into words, then kills any embedded commas.

    $_ = 'word 15,000 word word 20,000'; my @a = grep {s/(?<=\d),(?=\d)//g || $_} split;

      Why do you use grep here?
      $_ = 'word 0 word'; my @a = grep {s/(?<=\d),(?=\d)//g || $_} split;
      ...will of course lose data.
      $_ = 'word 0 word0,0word'; my @a = map {s/(?<=\d),(?=\d)//g; $_} split;
      ...will be better (as if there can be one wrong way better of another wrong way), but lose data too, btw.

        Tell me how it would "of course" lose data? It does work.

Re: changing a string to a numeric variable
by davido (Archbishop) on Mar 19, 2004 at 05:42 UTC
    Here's my take on it:

    Let's say you've got a string like this:

    my $string = "12 word 100,000 word 20,300 word word 180";

    And let's say that you want to split that string on whitespace into an array. You then wish to be able to perform mathematical operations on any of the numeric values, including the ones with commas in them.

    You also want the original string to be left in tact, but I get the impression it's ok for the split out values to be modified to facilitate coersion of numeric strings into numeric values.

    Ok, here goes...

    use strict; use warnings; my $string = "12 word 100,000 word 20,300 word word 180"; my @array = split /\s+/, $string; # Perform your split. $_ =~ tr/,//d for @array; # Tidy up, removing commas. $array[2] /= 10; # Do some math as a test. print "$array[2]\n"; # Print the results of the # math which we just performed # on a value which had previously # been a string.


Re: changing a string to a numeric variable
by revdiablo (Prior) on Mar 19, 2004 at 10:08 UTC

    Just to add a bit more info to the pile, try perldoc -q whole at a command prompt. It will list a bunch of different regular expressions useful for matching different kinds of string representations of numbers. Then once you read and digest some of those regular expressions (hopefully this isn't too much for a beginner, but hey, you gotta start somewhere), you might think about using Regexp::Common for convenience.

    Good luck on the journey.

Re: changing a string to a numeric variable
by pelagic (Priest) on Mar 18, 2004 at 22:02 UTC
    Find out for each $line[x] if it contains only digits and ',' (matching a regex). If that is the case, remove all ',' ( it might contain more than one in e.g. 3,120,000).

    I can resist anything but temptation.
Re: changing a string to a numeric variable
by cLive ;-) (Prior) on Mar 19, 2004 at 07:19 UTC
    @line = map { s/(\d),(\d)/$1$2/g; $_ } split;

    cLive ;-)

Re: changing a string to a numeric variable
by TomDLux (Vicar) on Mar 19, 2004 at 02:18 UTC

    You might want to delete commas only on numbers. If there's a possibility of other nun-numeric characters in numbers, you might delete those, as well.

    @numbers = map { /\d/ && s/\D//g } split $wholeLine; # # Or insist on leading digit? # @numbers = map { /^\d/ && s/\D//g } split $wholeLine;


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://337818]
Approved by kvale
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (2)
As of 2018-02-20 02:31 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (266 votes). Check out past polls.