⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 perlpacktut.1

📁 视频监控网络部分的协议ddns,的模块的实现代码,请大家大胆指正.
💻 1
📖 第 1 页 / 共 4 页
字号:
.\" 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 "PERLPACKTUT 1".TH PERLPACKTUT 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"perlpacktut \- tutorial on \f(CW\*(C`pack\*(C'\fR and \f(CW\*(C`unpack\*(C'\fR.SH "DESCRIPTION".IX Header "DESCRIPTION"\&\f(CW\*(C`pack\*(C'\fR and \f(CW\*(C`unpack\*(C'\fR are two functions for transforming data accordingto a user-defined template, between the guarded way Perl stores valuesand some well-defined representation as might be required in the environment of a Perl program. Unfortunately, they're also two of the most misunderstood and most often overlooked functions that Perlprovides. This tutorial will demystify them for you..SH "The Basic Principle".IX Header "The Basic Principle"Most programming languages don't shelter the memory where variables arestored. In C, for instance, you can take the address of some variable,and the \f(CW\*(C`sizeof\*(C'\fR operator tells you how many bytes are allocated tothe variable. Using the address and the size, you may access the storageto your heart's content..PPIn Perl, you just can't access memory at random, but the structural andrepresentational conversion provided by \f(CW\*(C`pack\*(C'\fR and \f(CW\*(C`unpack\*(C'\fR is anexcellent alternative. The \f(CW\*(C`pack\*(C'\fR function converts values to a bytesequence containing representations according to a given specification,the so-called \*(L"template\*(R" argument. \f(CW\*(C`unpack\*(C'\fR is the reverse process,deriving some values from the contents of a string of bytes. (Be cautioned,however, that not all that has been packed together can be neatly unpacked \- a very common experience as seasoned travellers are likely to confirm.).PPWhy, you may ask, would you need a chunk of memory containing some valuesin binary representation? One good reason is input and output accessingsome file, a device, or a network connection, whereby this binaryrepresentation is either forced on you or will give you some benefitin processing. Another cause is passing data to some system call thatis not available as a Perl function: \f(CW\*(C`syscall\*(C'\fR requires you to provideparameters stored in the way it happens in a C program. Even text processing (as shown in the next section) may be simplified with judicious usage of these two functions..PPTo see how (un)packing works, we'll start with a simple templatecode where the conversion is in low gear: between the contents of a bytesequence and a string of hexadecimal digits. Let's use \f(CW\*(C`unpack\*(C'\fR, sincethis is likely to remind you of a dump program, or some desperate lastmessage unfortunate programs are wont to throw at you before they expireinto the wild blue yonder. Assuming that the variable \f(CW$mem\fR holds a sequence of bytes that we'd like to inspect without assuming anything about its meaning, we can write.PP.Vb 2\&   my( $hex ) = unpack( \*(AqH*\*(Aq, $mem );\&   print "$hex\en";.Ve.PPwhereupon we might see something like this, with each pair of hex digitscorresponding to a byte:.PP.Vb 1\&   41204d414e204120504c414e20412043414e414c2050414e414d41.Ve.PPWhat was in this chunk of memory? Numbers, characters, or a mixture ofboth? Assuming that we're on a computer where \s-1ASCII\s0 (or some similar)encoding is used: hexadecimal values in the range \f(CW0x40\fR \- \f(CW0x5A\fRindicate an uppercase letter, and \f(CW0x20\fR encodes a space. So we mightassume it is a piece of text, which some are able to read like a tabloid;but others will have to get hold of an \s-1ASCII\s0 table and relive thatfirstgrader feeling. Not caring too much about which way to read this,we note that \f(CW\*(C`unpack\*(C'\fR with the template code \f(CW\*(C`H\*(C'\fR converts the contentsof a sequence of bytes into the customary hexadecimal notation. Since\&\*(L"a sequence of\*(R" is a pretty vague indication of quantity, \f(CW\*(C`H\*(C'\fR has beendefined to convert just a single hexadecimal digit unless it is followedby a repeat count. An asterisk for the repeat count means to use whateverremains..PPThe inverse operation \- packing byte contents from a string of hexadecimaldigits \- is just as easily written. For instance:.PP.Vb 2\&   my $s = pack( \*(AqH2\*(Aq x 10, map { "3$_" } ( 0..9 ) );\&   print "$s\en";.Ve.PPSince we feed a list of ten 2\-digit hexadecimal strings to \f(CW\*(C`pack\*(C'\fR, thepack template should contain ten pack codes. If this is run on a computerwith \s-1ASCII\s0 character coding, it will print \f(CW0123456789\fR..SH "Packing Text".IX Header "Packing Text"Let's suppose you've got to read in a data file like this:.PP.Vb 4\&    Date      |Description                | Income|Expenditure\&    01/24/2001 Ahmed\*(Aqs Camel Emporium                  1147.99\&    01/28/2001 Flea spray                                24.99\&    01/29/2001 Camel rides to tourists      235.00.Ve.PPHow do we do it? You might think first to use \f(CW\*(C`split\*(C'\fR; however, since\&\f(CW\*(C`split\*(C'\fR collapses blank fields, you'll never know whether a record wasincome or expenditure. Oops. Well, you could always use \f(CW\*(C`substr\*(C'\fR:.PP.Vb 7\&    while (<>) { \&        my $date   = substr($_,  0, 11);\&        my $desc   = substr($_, 12, 27);\&        my $income = substr($_, 40,  7);\&        my $expend = substr($_, 52,  7);\&        ...\&    }.Ve.PPIt's not really a barrel of laughs, is it? In fact, it's worse than itmay seem; the eagle-eyed may notice that the first field should only be10 characters wide, and the error has propagated right through the othernumbers \- which we've had to count by hand. So it's error-prone as wellas horribly unfriendly..PPOr maybe we could use regular expressions:.PP.Vb 5\&    while (<>) { \&        my($date, $desc, $income, $expend) = \&            m|(\ed\ed/\ed\ed/\ed{4}) (.{27}) (.{7})(.*)|;\&        ...\&    }.Ve.PPUrgh. Well, it's a bit better, but \- well, would you want to maintainthat?.PPHey, isn't Perl supposed to make this sort of thing easy? Well, it does,if you use the right tools. \f(CW\*(C`pack\*(C'\fR and \f(CW\*(C`unpack\*(C'\fR are designed to helpyou out when dealing with fixed-width data like the above. Let's have alook at a solution with \f(CW\*(C`unpack\*(C'\fR:.PP.Vb 4\&    while (<>) { \&        my($date, $desc, $income, $expend) = unpack("A10xA27xA7A*", $_);\&        ...\&    }.Ve.PPThat looks a bit nicer; but we've got to take apart that weird template.Where did I pull that out of?.PP\&\s-1OK\s0, let's have a look at some of our data again; in fact, we'll includethe headers, and a handy ruler so we can keep track of where we are..PP.Vb 5\&             1         2         3         4         5        \&    1234567890123456789012345678901234567890123456789012345678\&    Date      |Description                | Income|Expenditure\&    01/28/2001 Flea spray                                24.99\&    01/29/2001 Camel rides to tourists      235.00.Ve.PPFrom this, we can see that the date column stretches from column 1 tocolumn 10 \- ten characters wide. The \f(CW\*(C`pack\*(C'\fR\-ese for \*(L"character\*(R" is\&\f(CW\*(C`A\*(C'\fR, and ten of them are \f(CW\*(C`A10\*(C'\fR. So if we just wanted to extract thedates, we could say this:.PP.Vb 1\&    my($date) = unpack("A10", $_);.Ve.PP\&\s-1OK\s0, what's next? Between the date and the description is a blank column;we want to skip over that. The \f(CW\*(C`x\*(C'\fR template means \*(L"skip forward\*(R", so wewant one of those. Next, we have another batch of characters, from 12 to38. That's 27 more characters, hence \f(CW\*(C`A27\*(C'\fR. (Don't make the fenceposterror \- there are 27 characters between 12 and 38, not 26. Count 'em!).PPNow we skip another character and pick up the next 7 characters:.PP.Vb 1\&    my($date,$description,$income) = unpack("A10xA27xA7", $_);.Ve.PPNow comes the clever bit. Lines in our ledger which are just income andnot expenditure might end at column 46. Hence, we don't want to tell our\&\f(CW\*(C`unpack\*(C'\fR pattern that we \fBneed\fR to find another 12 characters; we'lljust say \*(L"if there's anything left, take it\*(R". As you might guess fromregular expressions, that's what the \f(CW\*(C`*\*(C'\fR means: \*(L"use everythingremaining\*(R"..IP "\(bu" 3Be warned, though, that unlike regular expressions, if the \f(CW\*(C`unpack\*(C'\fRtemplate doesn't match the incoming data, Perl will scream and die..PPHence, putting it all together:.PP.Vb 1\&    my($date,$description,$income,$expend) = unpack("A10xA27xA7xA*", $_);.Ve.PPNow, that's our data parsed. I suppose what we might want to do now istotal up our income and expenditure, and add another line to the end ofour ledger \- in the same format \- saying how much we've brought in andhow much we've spent:.PP.Vb 5\&    while (<>) {\&        my($date, $desc, $income, $expend) = unpack("A10xA27xA7xA*", $_);\&        $tot_income += $income;\&        $tot_expend += $expend;\&    }\&\&    $tot_income = sprintf("%.2f", $tot_income); # Get them into \&    $tot_expend = sprintf("%.2f", $tot_expend); # "financial" format\&\&    $date = POSIX::strftime("%m/%d/%Y", localtime); \&\&    # OK, let\*(Aqs go:\&\&    print pack("A10xA27xA7xA*", $date, "Totals", $tot_income, $tot_expend);.Ve.PPOh, hmm. That didn't quite work. Let's see what happened:.PP.Vb 4\&    01/24/2001 Ahmed\*(Aqs Camel Emporium                   1147.99\&    01/28/2001 Flea spray                                 24.99\&    01/29/2001 Camel rides to tourists     1235.00\&    03/23/2001Totals                     1235.001172.98

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -