Perl: Convert from srting to number

Actually there is no specific variable existence like string, integer, etc at Perl. All are called Scalar, and it takes all at the same time. The variable type changes from string to integer depending upon the value, or state.

For example depending upon value $string = "test"; is a string. But if you set the $string with 10, it will act as integer. $string = 10;

For example depending upon state, $string + 10, here $string will act as integer. And here if($string ge "100") $string will act as string.

But still, you can convert your string into integer easily using int() function.
my $string = "10";
$string = int($string); ## convert
print "$string\n";


Or, you can use sprintf() function to do the conversion.
my $string = "10";
$string = sprintf("%d", $string); ## convert
print "$string\n";


But still, both the conversion are useless. I still suggest you to assign the values directly instead of using the functions.

Comments

Nitrous Gold said…
These conversions are not useless. They can be helpful in input cleaning, among other places. For example, consider the following code.


while(<>){
    chomp;
    $x = int($_);
    print "SomeSQLCommand($x)";
}

versus leaving out the int

while(<>){
    chomp;
    $x = $_;
    print "SomeSQLCommand($x)";
}



If fed the file

1
2
3
maliciousInput


The first produces

SomeSQLCommand(1)
SomeSQLCommand(2)
SomeSQLCommand(3)
SomeSQLCommand(0)


Whereas the second produces

SomeSQLCommand(1)
SomeSQLCommand(2)
SomeSQLCommand(3)
SomeSQLCommand(maliciousInput)

The int conversion call ensures that the untrustworthy file can only produce integer input.
Anonymous said…
This blog helped me with conversion issue. Thanks!