In this second part of a five-part series on scalars in Perl, you'll learn about operators (both arithmetic and bitwise), among other things. This article is excerpted from chapter two of the book Beginning Perl, written by James Lee (Apress; ISBN: 159059391X).
Perl treats numbers and strings on an equal footing, and where necessary, Perl converts between strings, integers, and floating point numbers behind the scenes. There is a special term for this: automatic conversion of scalars. This means that you donít have to worry about making the conversions yourself, like you do in other languages. If you have a string literal "0.25", and multiply it by four, Perl treats it as a number and gives you the expected answer, 1. For example:
#!/usr/bin/perl -w # autoconvert.pl
print "0.25" * 4, "\n";
The asterisk (*) is the multiplication operator. All of Perlís operators, including this one, will be discussed in the next section.
There is, however, one area where this automatic conversion does not take place. Octal, hex, and binary numbers in string literals or strings stored in variables donít get converted automatically.
#!/usr/bin/perl -w # octhex1.pl
print "0x30\n"; print "030\n";
$ perl octhex1.pl 0x30 030 $
If you ever find yourself with a string containing a hex or octal value that you need to convert into a number, you can use thehex()oroct()functions accordingly:
#!/usr/bin/perl -w # octhex2.pl
print hex("0x30"), "\n"; print oct("030"), "\n";
This will now produce the expected answers, 48 and 24. Note that forhex()oroct(), the prefix0x or0respectively is not required. If you know that what you have is definitely supposed to be a hex or octal number, thenhex(30)andoct(30)will produce the preceding results. As you can see from that, the string"30"and the number30 are treated as the same.
Furthermore, these functions will stop reading when they get to a digit that doesnít make sense in that number system:
#!/usr/bin/perl -w # octhex3.pl
print hex("FFG"), "\n"; print oct("178"), "\n";
These will stop atFFand17respectively, and convert to 255 and 15. Perl will warn you, though, since those are illegal characters in hex and octal numbers.
What about binary numbers? Well, thereís no correspondingbin()function but there is actually a little trick here. If you have the correct prefix in place for any of the number systems (0,0b, or0x), you can useoct()to convert it to decimal. For example, print oct("0b11010")prints 26.