10.07.2015 Views

Beginning Web Development With Perl : From Novice to ... - Nabo

Beginning Web Development With Perl : From Novice to ... - Nabo

Beginning Web Development With Perl : From Novice to ... - Nabo

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

292APPENDIX ■ PERL BASICSBy default, a here-document works like a double-quoted string. In order for it <strong>to</strong> work likea single-quoted string, surround the label in single quotes. This will become important whenvariable interpolation comes in<strong>to</strong> play, as you’ll see later on.Converting Between Numbers and Strings<strong>Perl</strong> treats numbers and strings on an equal footing, and where necessary, <strong>Perl</strong> convertsbetween strings, integers, and floating-point numbers behind the scenes. There is a specialterm for this: au<strong>to</strong>matic conversion of scalars. This means that you don’t have <strong>to</strong> worry aboutmaking the conversions yourself, like you do in other languages. If you have a string literal"0.25" and multiply it by 4, <strong>Perl</strong> treats it as a number and gives you the expected answer, 1. Forexample:#!/usr/bin/perl -w# au<strong>to</strong>convert.plprint "0.25" * 4, "\ n";The asterisk (*) is the multiplication opera<strong>to</strong>r. All of <strong>Perl</strong>’s opera<strong>to</strong>rs, including this one,are discussed in the next section.There is, however, one area where this au<strong>to</strong>matic conversion does not take place. Octal,hex, and binary numbers in string literals or strings s<strong>to</strong>red in variables don’t get convertedau<strong>to</strong>matically.#!/usr/bin/perl -w# octhex1.plprint "0x30\ n";print "030\ n";gives you$ perl octhex1.pl0x30030$If you ever find yourself with a string containing a hex or octal value that you need <strong>to</strong> convertin<strong>to</strong> a number, you can use the hex() or oct() functions accordingly:#!/usr/bin/perl -w# octhex2.plprint hex("0x30"), "\ n";print oct("030"), "\ n";This will now produce the expected answers, 48 and 24. Note that for hex() or oct(), theprefix 0x or 0, respectively, is not required. If you know that what you have is definitely supposed<strong>to</strong> be a hex or octal number, then hex(30) and oct(30) will produce the precedingresults. As you can see from that, the string "30" and the number 30 are treated as the same.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!