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

Hi Monks and Monkesesss,

How can I convert the string 36 to the integer 36?

I don't just mean 36 but any number stored as a string.

I have a list of rules and associated with each rule there are two digits

So, I have a hash with the ruleids as the keys and the two integers are added like this, 36+10, and stored as a string.

Later when I want the two separate integers I split on + to get them but I now have two strings and I want two integers.

Helpeth,

Fian.
Aontroim Abú.

Replies are listed 'Best First'.
Re: string to scalar?
by larsen (Parson) on Jun 20, 2001 at 14:12 UTC
    From perldata...

    Scalars aren't necessarily one thing or another. There's no place to declare a scalar variable to be of type "string", or of type "number", or type "filehandle", or anything else. Perl is a contextually polymorphic language whose scalars can be strings, numbers, or references (which includes objects). While strings and numbers are considered pretty much the same thing for nearly all purposes, references are strongly-typed uncastable pointers with builtin reference-counting and destructor invocation.

    You could find further infos on this article by Tom Christiansen: Is it a number?

Re: string to scalar?
by busunsl (Vicar) on Jun 20, 2001 at 14:04 UTC
    You don't have to convert the string, you can just use it as an integer.
    Perl does the conversion automagically for you.

    Example:

    $x = "36"; $y = $x * 2; print $y; gives 72
Re: string to scalar?
by virtualsue (Vicar) on Jun 20, 2001 at 14:27 UTC
    Hi Fian,

    Because Perl is a weakly-typed language, there is no "string" or "integer" data type as such. Scalars variables are numbers or strings, depending on how you use them.

    If you have $num1 = "36" and $num2 = "10", then if you do: $sum = $num1 + $num2 $sum will be equal 46.

Re: string to scalar?
by perchance (Monk) on Jun 20, 2001 at 14:35 UTC
    I believe the important thing to understand (and this may not be a precise definition), is
    that the context in which you use a scalar determines how it is manipulated.
    That's why there are, for example, different operators == !=for numbers, eq ne for strings.
    You can read more on this in perldata, under 'scalars'.

    --- perchance

Re: string to scalar?
by jplindstrom (Monsignor) on Jun 20, 2001 at 16:46 UTC
    As many have already commented, it's all about context.

    One way of forcing numeric context is to simply add nothing (say, if you have $num = "2.750000"):

    $num += 0;

    And, if you really need an integer, use int($num).

    /J