Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a string to a number in Perl?

I have a string which holds a decimal value in it and I need to convert that string into a floating point variable. So an example of the string I have is "5.45" and I want a floating point equivalent so I can add .1 to it. I have searched around the internet, but I only see how to convert a string to an integer.

like image 793
Anton Avatar asked Nov 14 '08 00:11

Anton


People also ask

What is $_ in Perl?

The most commonly used special variable is $_, which contains the default input and pattern-searching string. For example, in the following lines − #!/usr/bin/perl foreach ('hickory','dickory','doc') { print $_; print "\n"; }

How do I convert 0 to string in Perl?

my $x = 0; print qq("$x"); prints "0" .

What is =~ in Perl script?

9.3. The Binding Operator, =~ Matching against $_ is merely the default; the binding operator (=~) tells Perl to match the pattern on the right against the string on the left, instead of matching against $_.


2 Answers

You don't need to convert it at all:

% perl -e 'print "5.45" + 0.1;' 5.55 
like image 104
Alnitak Avatar answered Sep 23 '22 05:09

Alnitak


This is a simple solution:

Example 1

my $var1 = "123abc"; print $var1 + 0; 

Result

123 

Example 2

my $var2 = "abc123"; print $var2 + 0; 

Result

0 
like image 35
porquero Avatar answered Sep 19 '22 05:09

porquero