📄 perlfaq4.1
字号:
.\" Automatically generated by Pod::Man 2.16 (Pod::Simple 3.05).\".\" Standard preamble:.\" ========================================================================.de Sh \" Subsection heading.br.if t .Sp.ne 5.PP\fB\\$1\fR.PP...de Sp \" Vertical space (when we can't use .PP).if t .sp .5v.if n .sp...de Vb \" Begin verbatim text.ft CW.nf.ne \\$1...de Ve \" End verbatim text.ft R.fi...\" Set up some character translations and predefined strings. \*(-- will.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left.\" double quote, and \*(R" will give a right double quote. \*(C+ will.\" give a nicer C++. Capital omega is used to do unbreakable dashes and.\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff,.\" nothing in troff, for use with C<>..tr \(*W-.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'.ie n \{\. ds -- \(*W-. ds PI pi. if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch. if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch. ds L" "". ds R" "". ds C` "". ds C' ""'br\}.el\{\. ds -- \|\(em\|. ds PI \(*p. ds L" ``. ds R" '''br\}.\".\" Escape single quotes in literal strings from groff's Unicode transform..ie \n(.g .ds Aq \(aq.el .ds Aq '.\".\" If the F register is turned on, we'll generate index entries on stderr for.\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index.\" entries marked with X<> in POD. Of course, you'll have to process the.\" output yourself in some meaningful fashion..ie \nF \{\. de IX. tm Index:\\$1\t\\n%\t"\\$2"... nr % 0. rr F.\}.el \{\. de IX...\}.\".\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2)..\" Fear. Run. Save yourself. No user-serviceable parts.. \" fudge factors for nroff and troff.if n \{\. ds #H 0. ds #V .8m. ds #F .3m. ds #[ \f1. ds #] \fP.\}.if t \{\. ds #H ((1u-(\\\\n(.fu%2u))*.13m). ds #V .6m. ds #F 0. ds #[ \&. ds #] \&.\}. \" simple accents for nroff and troff.if n \{\. ds ' \&. ds ` \&. ds ^ \&. ds , \&. ds ~ ~. ds /.\}.if t \{\. ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u". ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'. ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'. ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'. ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'. ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'.\}. \" troff and (daisy-wheel) nroff accents.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'.ds 8 \h'\*(#H'\(*b\h'-\*(#H'.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#].ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#].ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#].ds ae a\h'-(\w'a'u*4/10)'e.ds Ae A\h'-(\w'A'u*4/10)'E. \" corrections for vroff.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'. \" for low resolution devices (crt and lpr).if \n(.H>23 .if \n(.V>19 \\{\. ds : e. ds 8 ss. ds o a. ds d- d\h'-1'\(ga. ds D- D\h'-1'\(hy. ds th \o'bp'. ds Th \o'LP'. ds ae ae. ds Ae AE.\}.rm #[ #] #H #V #F C.\" ========================================================================.\".IX Title "PERLFAQ4 1".TH PERLFAQ4 1 "2007-12-18" "perl v5.10.0" "Perl Programmers Reference Guide".\" For nroff, turn off justification. Always turn off hyphenation; it makes.\" way too many mistakes in technical documents..if n .ad l.nh.SH "NAME"perlfaq4 \- Data Manipulation ($Revision: 10394 $).SH "DESCRIPTION".IX Header "DESCRIPTION"This section of the \s-1FAQ\s0 answers questions related to manipulatingnumbers, dates, strings, arrays, hashes, and miscellaneous data issues..SH "Data: Numbers".IX Header "Data: Numbers".Sh "Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)?".IX Subsection "Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)?"Internally, your computer represents floating-point numbers in binary.Digital (as in powers of two) computers cannot store all numbersexactly. Some real numbers lose precision in the process. This is aproblem with how computers store numbers and affects all computerlanguages, not just Perl..PPperlnumber shows the gory details of number representations andconversions..PPTo limit the number of decimal places in your numbers, you can use theprintf or sprintf function. See the \*(L"Floating PointArithmetic\*(R" for more details..PP.Vb 1\& printf "%.2f", 10/3;\&\& my $number = sprintf "%.2f", 10/3;.Ve.Sh "Why is \fIint()\fP broken?".IX Subsection "Why is int() broken?"Your \f(CW\*(C`int()\*(C'\fR is most probably working just fine. It's the numbers thataren't quite what you think..PPFirst, see the answer to \*(L"Why am I getting long decimals(eg, 19.9499999999999) instead of the numbers I should be getting(eg, 19.95)?\*(R"..PPFor example, this.PP.Vb 1\& print int(0.6/0.2\-2), "\en";.Ve.PPwill in most computers print 0, not 1, because even such simplenumbers as 0.6 and 0.2 cannot be presented exactly by floating-pointnumbers. What you think in the above as 'three' is really more like2.9999999999999995559..Sh "Why isn't my octal data interpreted correctly?".IX Subsection "Why isn't my octal data interpreted correctly?"Perl only understands octal and hex numbers as such when they occur asliterals in your program. Octal literals in perl must start with aleading \f(CW0\fR and hexadecimal literals must start with a leading \f(CW\*(C`0x\*(C'\fR.If they are read in from somewhere and assigned, no automaticconversion takes place. You must explicitly use \f(CW\*(C`oct()\*(C'\fR or \f(CW\*(C`hex()\*(C'\fR if youwant the values converted to decimal. \f(CW\*(C`oct()\*(C'\fR interprets hexadecimal (\f(CW0x350\fR),octal (\f(CW0350\fR or even without the leading \f(CW0\fR, like \f(CW377\fR) and binary(\f(CW\*(C`0b1010\*(C'\fR) numbers, while \f(CW\*(C`hex()\*(C'\fR only converts hexadecimal ones, withor without a leading \f(CW\*(C`0x\*(C'\fR, such as \f(CW0x255\fR, \f(CW\*(C`3A\*(C'\fR, \f(CW\*(C`ff\*(C'\fR, or \f(CW\*(C`deadbeef\*(C'\fR.The inverse mapping from decimal to octal can be done with either the<%o> or \f(CW%O\fR \f(CW\*(C`sprintf()\*(C'\fR formats..PPThis problem shows up most often when people try using \f(CW\*(C`chmod()\*(C'\fR,\&\f(CW\*(C`mkdir()\*(C'\fR, \f(CW\*(C`umask()\*(C'\fR, or \f(CW\*(C`sysopen()\*(C'\fR, which by widespread traditiontypically take permissions in octal..PP.Vb 2\& chmod(644, $file); # WRONG\& chmod(0644, $file); # right.Ve.PPNote the mistake in the first line was specifying the decimal literal\&\f(CW644\fR, rather than the intended octal literal \f(CW0644\fR. The problem canbe seen with:.PP.Vb 1\& printf("%#o",644); # prints 01204.Ve.PPSurely you had not intended \f(CW\*(C`chmod(01204, $file);\*(C'\fR \- did you? If youwant to use numeric literals as arguments to \fIchmod()\fR et al. then pleasetry to express them as octal constants, that is with a leading zero andwith the following digits restricted to the set \f(CW0..7\fR..Sh "Does Perl have a \fIround()\fP function? What about \fIceil()\fP and \fIfloor()\fP? Trig functions?".IX Subsection "Does Perl have a round() function? What about ceil() and floor()? Trig functions?"Remember that \f(CW\*(C`int()\*(C'\fR merely truncates toward 0. For rounding to acertain number of digits, \f(CW\*(C`sprintf()\*(C'\fR or \f(CW\*(C`printf()\*(C'\fR is usually theeasiest route..PP.Vb 1\& printf("%.3f", 3.1415926535); # prints 3.142.Ve.PPThe \f(CW\*(C`POSIX\*(C'\fR module (part of the standard Perl distribution)implements \f(CW\*(C`ceil()\*(C'\fR, \f(CW\*(C`floor()\*(C'\fR, and a number of other mathematicaland trigonometric functions..PP.Vb 3\& use POSIX;\& $ceil = ceil(3.5); # 4\& $floor = floor(3.5); # 3.Ve.PPIn 5.000 to 5.003 perls, trigonometry was done in the \f(CW\*(C`Math::Complex\*(C'\fRmodule. With 5.004, the \f(CW\*(C`Math::Trig\*(C'\fR module (part of the standard Perldistribution) implements the trigonometric functions. Internally ituses the \f(CW\*(C`Math::Complex\*(C'\fR module and some functions can break out fromthe real axis into the complex plane, for example the inverse sine of2..PPRounding in financial applications can have serious implications, andthe rounding method used should be specified precisely. In thesecases, it probably pays not to trust whichever system rounding isbeing used by Perl, but to instead implement the rounding function youneed yourself..PPTo see why, notice how you'll still have an issue on half-way-pointalternation:.PP.Vb 1\& for ($i = 0; $i < 1.01; $i += 0.05) { printf "%.1f ",$i}\&\& 0.0 0.1 0.1 0.2 0.2 0.2 0.3 0.3 0.4 0.4 0.5 0.5 0.6 0.7 0.7\& 0.8 0.8 0.9 0.9 1.0 1.0.Ve.PPDon't blame Perl. It's the same as in C. \s-1IEEE\s0 says we have to dothis. Perl numbers whose absolute values are integers under 2**31 (on32 bit machines) will work pretty much like mathematical integers.Other numbers are not guaranteed..Sh "How do I convert between numeric representations/bases/radixes?".IX Subsection "How do I convert between numeric representations/bases/radixes?"As always with Perl there is more than one way to do it. Below are afew examples of approaches to making common conversions between numberrepresentations. This is intended to be representational rather thanexhaustive..PPSome of the examples later in perlfaq4 use the \f(CW\*(C`Bit::Vector\*(C'\fRmodule from \s-1CPAN\s0. The reason you might choose \f(CW\*(C`Bit::Vector\*(C'\fR over theperl built in functions is that it works with numbers of \s-1ANY\s0 size,that it is optimized for speed on some operations, and for at leastsome programmers the notation might be familiar..IP "How do I convert hexadecimal into decimal" 4.IX Item "How do I convert hexadecimal into decimal"Using perl's built in conversion of \f(CW\*(C`0x\*(C'\fR notation:.Sp.Vb 1\& $dec = 0xDEADBEEF;.Ve.SpUsing the \f(CW\*(C`hex\*(C'\fR function:.Sp.Vb 1\& $dec = hex("DEADBEEF");.Ve.SpUsing \f(CW\*(C`pack\*(C'\fR:.Sp.Vb 1\& $dec = unpack("N", pack("H8", substr("0" x 8 . "DEADBEEF", \-8)));.Ve.SpUsing the \s-1CPAN\s0 module \f(CW\*(C`Bit::Vector\*(C'\fR:.Sp.Vb 3\& use Bit::Vector;\& $vec = Bit::Vector\->new_Hex(32, "DEADBEEF");\& $dec = $vec\->to_Dec();.Ve.IP "How do I convert from decimal to hexadecimal" 4.IX Item "How do I convert from decimal to hexadecimal"Using \f(CW\*(C`sprintf\*(C'\fR:.Sp.Vb 2\& $hex = sprintf("%X", 3735928559); # upper case A\-F\& $hex = sprintf("%x", 3735928559); # lower case a\-f.Ve.SpUsing \f(CW\*(C`unpack\*(C'\fR:.Sp.Vb 1\& $hex = unpack("H*", pack("N", 3735928559));.Ve.SpUsing \f(CW\*(C`Bit::Vector\*(C'\fR:.Sp.Vb 3\& use Bit::Vector;\& $vec = Bit::Vector\->new_Dec(32, \-559038737);\& $hex = $vec\->to_Hex();.Ve.SpAnd \f(CW\*(C`Bit::Vector\*(C'\fR supports odd bit counts:.Sp.Vb 4\& use Bit::Vector;\& $vec = Bit::Vector\->new_Dec(33, 3735928559);\& $vec\->Resize(32); # suppress leading 0 if unwanted\& $hex = $vec\->to_Hex();.Ve.IP "How do I convert from octal to decimal" 4.IX Item "How do I convert from octal to decimal"Using Perl's built in conversion of numbers with leading zeros:.Sp.Vb 1\& $dec = 033653337357; # note the leading 0!.Ve.SpUsing the \f(CW\*(C`oct\*(C'\fR function:.Sp.Vb 1\& $dec = oct("33653337357");.Ve
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -