- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to convert a string to a number in Perl?
In Perl, we can convert a string into a number by appending the integer value 0 in front of it. There are some other approaches too, which we will discuss in this tutorial with the help of examples.
Example
Let's first consider the case where the string that we are trying to convert looks something like "123abc" or "23Hzbc". You can see that the it is a mixture of both integer values and characters. Consider the code shown below.
my $firstStr = '23ASDF'; print "Convering First String to Number: ", $firstStr + 0; print "\n"; my $secondStr = '123abc'; print "Convering Second String to Number: ", $secondStr + 0;
Output
In the above code, we are just appending the number "0" to convert the given string to an integer. Click "Edit and Run" and check the output of this code −
Convering First String to Number: 23 Convering Second String to Number: 123
Example
Now, let's consider another case where our string looks something like "abc" or "Hello". Consider the code shown below.
my $str = 'Hello'; print "Converting String to Number: ", $str + 100; print "\n"; my $anotherStr = 'Sample'; print "Converting String to Number: ", $anotherStr + 0;
Output
In the above code, we are just appending the number 0 and number 100 to convert the string to an integer. Click "Edit and Run" and check the output −
Converting String to Number: 100 Converting String to Number: 0
Example
The other approach to convert a string to a number in Perl is to just append two strings, to get an integer value. Consider the code shown below.
my $sum = '5.45' + '0.01'; my $anotherSum = '5.01' + '0.07'; print "Addition 1: ", $sum; print "\n"; print "Addition 2: ", $anotherSum;
Output
Click "Edit and Run" to check the output of this code −
Addition 1: 5.46 Addition 2: 5.08
Conclusion
In this tutorial, we used a few simple examples to demonstrate how you can convert a string to a number in Perl.