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

📄 perldata.pod

📁 视频监控网络部分的协议ddns,的模块的实现代码,请大家大胆指正.
💻 POD
📖 第 1 页 / 共 3 页
字号:
    ($dev, $ino, undef, undef, $uid, $gid) = stat($file);List assignment in scalar context returns the number of elementsproduced by the expression on the right side of the assignment:    $x = (($foo,$bar) = (3,2,1));       # set $x to 3, not 2    $x = (($foo,$bar) = f());           # set $x to f()'s return countThis is handy when you want to do a list assignment in a Booleancontext, because most list functions return a null list when finished,which when assigned produces a 0, which is interpreted as FALSE.It's also the source of a useful idiom for executing a function orperforming an operation in list context and then counting the number ofreturn values, by assigning to an empty list and then using thatassignment in scalar context. For example, this code:    $count = () = $string =~ /\d+/g;will place into $count the number of digit groups found in $string.This happens because the pattern match is in list context (since itis being assigned to the empty list), and will therefore return a listof all matching parts of the string. The list assignment in scalarcontext will translate that into the number of elements (here, thenumber of times the pattern matched) and assign that to $count. Notethat simply using    $count = $string =~ /\d+/g;would not have worked, since a pattern match in scalar context willonly return true or false, rather than a count of matches.The final element of a list assignment may be an array or a hash:    ($a, $b, @rest) = split;    my($a, $b, %rest) = @_;You can actually put an array or hash anywhere in the list, but the first onein the list will soak up all the values, and anything after it will becomeundefined.  This may be useful in a my() or local().A hash can be initialized using a literal list holding pairs ofitems to be interpreted as a key and a value:    # same as map assignment above    %map = ('red',0x00f,'blue',0x0f0,'green',0xf00);While literal lists and named arrays are often interchangeable, that'snot the case for hashes.  Just because you can subscript a list value likea normal array does not mean that you can subscript a list value as ahash.  Likewise, hashes included as parts of other lists (includingparameters lists and return lists from functions) always flatten out intokey/value pairs.  That's why it's good to use references sometimes.It is often more readable to use the C<< => >> operator between key/valuepairs.  The C<< => >> operator is mostly just a more visually distinctivesynonym for a comma, but it also arranges for its left-hand operand to beinterpreted as a string -- if it's a bareword that would be a legal simpleidentifier (C<< => >> doesn't quote compound identifiers, that containdouble colons). This makes it nice for initializing hashes:    %map = (                 red   => 0x00f,                 blue  => 0x0f0,                 green => 0xf00,   );or for initializing hash references to be used as records:    $rec = {                witch => 'Mable the Merciless',                cat   => 'Fluffy the Ferocious',                date  => '10/31/1776',    };or for using call-by-named-parameter to complicated functions:   $field = $query->radio_group(               name      => 'group_name',               values    => ['eenie','meenie','minie'],               default   => 'meenie',               linebreak => 'true',               labels    => \%labels   );Note that just because a hash is initialized in that order doesn'tmean that it comes out in that order.  See L<perlfunc/sort> for examplesof how to arrange for an output ordering.=head2 SubscriptsAn array is subscripted by specifying a dollar sign (C<$>), then thename of the array (without the leading C<@>), then the subscript insidesquare brackets.  For example:    @myarray = (5, 50, 500, 5000);    print "Element Number 2 is", $myarray[2], "\n";The array indices start with 0. A negative subscript retrieves its value from the end.  In our example, C<$myarray[-1]> would have been 5000, and C<$myarray[-2]> would have been 500.Hash subscripts are similar, only instead of square brackets curly bracketsare used. For example:    %scientists =     (        "Newton" => "Isaac",        "Einstein" => "Albert",        "Darwin" => "Charles",        "Feynman" => "Richard",    );    print "Darwin's First Name is ", $scientists{"Darwin"}, "\n";=head2 SlicesX<slice> X<array, slice> X<hash, slice>A common way to access an array or a hash is one scalar element at atime.  You can also subscript a list to get a single element from it.    $whoami = $ENV{"USER"};             # one element from the hash    $parent = $ISA[0];                  # one element from the array    $dir    = (getpwnam("daemon"))[7];  # likewise, but with listA slice accesses several elements of a list, an array, or a hashsimultaneously using a list of subscripts.  It's more convenientthan writing out the individual elements as a list of separatescalar values.    ($him, $her)   = @folks[0,-1];              # array slice    @them          = @folks[0 .. 3];            # array slice    ($who, $home)  = @ENV{"USER", "HOME"};      # hash slice    ($uid, $dir)   = (getpwnam("daemon"))[2,7]; # list sliceSince you can assign to a list of variables, you can also assign toan array or hash slice.    @days[3..5]    = qw/Wed Thu Fri/;    @colors{'red','blue','green'}                    = (0xff0000, 0x0000ff, 0x00ff00);    @folks[0, -1]  = @folks[-1, 0];The previous assignments are exactly equivalent to    ($days[3], $days[4], $days[5]) = qw/Wed Thu Fri/;    ($colors{'red'}, $colors{'blue'}, $colors{'green'})                   = (0xff0000, 0x0000ff, 0x00ff00);    ($folks[0], $folks[-1]) = ($folks[-1], $folks[0]);Since changing a slice changes the original array or hash that it'sslicing, a C<foreach> construct will alter some--or even all--of thevalues of the array or hash.    foreach (@array[ 4 .. 10 ]) { s/peter/paul/ }     foreach (@hash{qw[key1 key2]}) {        s/^\s+//;           # trim leading whitespace        s/\s+$//;           # trim trailing whitespace        s/(\w+)/\u\L$1/g;   # "titlecase" words    }A slice of an empty list is still an empty list.  Thus:    @a = ()[1,0];           # @a has no elements    @b = (@a)[0,1];         # @b has no elements    @c = (0,1)[2,3];        # @c has no elementsBut:    @a = (1)[1,0];          # @a has two elements    @b = (1,undef)[1,0,2];  # @b has three elementsThis makes it easy to write loops that terminate when a null listis returned:    while ( ($home, $user) = (getpwent)[7,0]) {        printf "%-8s %s\n", $user, $home;    }As noted earlier in this document, the scalar sense of list assignmentis the number of elements on the right-hand side of the assignment.The null list contains no elements, so when the password file isexhausted, the result is 0, not 2.If you're confused about why you use an '@' there on a hash sliceinstead of a '%', think of it like this.  The type of bracket (squareor curly) governs whether it's an array or a hash being looked at.On the other hand, the leading symbol ('$' or '@') on the array orhash indicates whether you are getting back a singular value (ascalar) or a plural one (a list).=head2 Typeglobs and FilehandlesX<typeglob> X<filehandle> X<*>Perl uses an internal type called a I<typeglob> to hold an entiresymbol table entry.  The type prefix of a typeglob is a C<*>, becauseit represents all types.  This used to be the preferred way topass arrays and hashes by reference into a function, but now thatwe have real references, this is seldom needed.  The main use of typeglobs in modern Perl is create symbol table aliases.This assignment:    *this = *that;makes $this an alias for $that, @this an alias for @that, %this an aliasfor %that, &this an alias for &that, etc.  Much safer is to use a reference.This:    local *Here::blue = \$There::green;temporarily makes $Here::blue an alias for $There::green, but doesn'tmake @Here::blue an alias for @There::green, or %Here::blue an alias for%There::green, etc.  See L<perlmod/"Symbol Tables"> for more examplesof this.  Strange though this may seem, this is the basis for the wholemodule import/export system.Another use for typeglobs is to pass filehandles into a function orto create new filehandles.  If you need to use a typeglob to save awaya filehandle, do it this way:    $fh = *STDOUT;or perhaps as a real reference, like this:    $fh = \*STDOUT;See L<perlsub> for examples of using these as indirect filehandlesin functions.Typeglobs are also a way to create a local filehandle using the local()operator.  These last until their block is exited, but may be passed back.For example:    sub newopen {        my $path = shift;        local  *FH;  # not my!        open   (FH, $path)          or  return undef;        return *FH;    }    $fh = newopen('/etc/passwd');Now that we have the C<*foo{THING}> notation, typeglobs aren't used as muchfor filehandle manipulations, although they're still needed to pass brandnew file and directory handles into or out of functions. That's becauseC<*HANDLE{IO}> only works if HANDLE has already been used as a handle.In other words, C<*FH> must be used to create new symbol table entries;C<*foo{THING}> cannot.  When in doubt, use C<*FH>.All functions that are capable of creating filehandles (open(),opendir(), pipe(), socketpair(), sysopen(), socket(), and accept())automatically create an anonymous filehandle if the handle passed tothem is an uninitialized scalar variable. This allows the constructssuch as C<open(my $fh, ...)> and C<open(local $fh,...)> to be used tocreate filehandles that will conveniently be closed automatically whenthe scope ends, provided there are no other references to them. Thislargely eliminates the need for typeglobs when opening filehandlesthat must be passed around, as in the following example:    sub myopen {        open my $fh, "@_"             or die "Can't open '@_': $!";        return $fh;    }    {        my $f = myopen("</etc/motd");        print <$f>;        # $f implicitly closed here    }Note that if an initialized scalar variable is used instead theresult is different: C<my $fh='zzz'; open($fh, ...)> is equivalentto C<open( *{'zzz'}, ...)>.C<use strict 'refs'> forbids such practice.Another way to create anonymous filehandles is with the Symbolmodule or with the IO::Handle module and its ilk.  These moduleshave the advantage of not hiding different types of the same nameduring the local().  See the bottom of L<perlfunc/open()> for anexample.=head1 SEE ALSOSee L<perlvar> for a description of Perl's built-in variables anda discussion of legal variable names.  See L<perlref>, L<perlsub>,and L<perlmod/"Symbol Tables"> for more discussion on typeglobs andthe C<*foo{THING}> syntax.

⌨️ 快捷键说明

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