perlfaq7.pod
来自「视频监控网络部分的协议ddns,的模块的实现代码,请大家大胆指正.」· POD 代码 · 共 1,034 行 · 第 1/3 页
POD
1,034 行
If one wants to use pure Perl and to be compatible with Perl versionsprior to 5.10, the general answer is to write a construct like this: for ($variable_to_test) { if (/pat1/) { } # do something elsif (/pat2/) { } # do something else elsif (/pat3/) { } # do something else else { } # default }Here's a simple example of a switch based on pattern matching,lined up in a way to make it look more like a switch statement.We'll do a multiway conditional based on the type of reference storedin $whatchamacallit: SWITCH: for (ref $whatchamacallit) { /^$/ && die "not a reference"; /SCALAR/ && do { print_scalar($$ref); last SWITCH; }; /ARRAY/ && do { print_array(@$ref); last SWITCH; }; /HASH/ && do { print_hash(%$ref); last SWITCH; }; /CODE/ && do { warn "can't print function ref"; last SWITCH; }; # DEFAULT warn "User defined type skipped"; }See L<perlsyn> for other examples in this style.Sometimes you should change the positions of the constant and the variable.For example, let's say you wanted to test which of many answers you weregiven, but in a case-insensitive way that also allows abbreviations.You can use the following technique if the strings all start withdifferent characters or if you want to arrange the matches so thatone takes precedence over another, as C<"SEND"> has precedence overC<"STOP"> here: chomp($answer = <>); if ("SEND" =~ /^\Q$answer/i) { print "Action is send\n" } elsif ("STOP" =~ /^\Q$answer/i) { print "Action is stop\n" } elsif ("ABORT" =~ /^\Q$answer/i) { print "Action is abort\n" } elsif ("LIST" =~ /^\Q$answer/i) { print "Action is list\n" } elsif ("EDIT" =~ /^\Q$answer/i) { print "Action is edit\n" }A totally different approach is to create a hash of function references. my %commands = ( "happy" => \&joy, "sad", => \&sullen, "done" => sub { die "See ya!" }, "mad" => \&angry, ); print "How are you? "; chomp($string = <STDIN>); if ($commands{$string}) { $commands{$string}->(); } else { print "No such command: $string\n"; }Note that starting from version 5.10, Perl has now a native switchstatement. See L<perlsyn>.Starting from Perl 5.8, a source filter module, C<Switch>, can also beused to get switch and case. Its use is now discouraged, because it'snot fully compatible with the native switch of Perl 5.10, and because,as it's implemented as a source filter, it doesn't always work as intendedwhen complex syntax is involved.=head2 How can I catch accesses to undefined variables, functions, or methods?The AUTOLOAD method, discussed in L<perlsub/"Autoloading"> andL<perltoot/"AUTOLOAD: Proxy Methods">, lets you capture calls toundefined functions and methods.When it comes to undefined variables that would trigger a warningunder C<use warnings>, you can promote the warning to an error. use warnings FATAL => qw(uninitialized);=head2 Why can't a method included in this same file be found?Some possible reasons: your inheritance is getting confused, you'vemisspelled the method name, or the object is of the wrong type. Checkout L<perltoot> for details about any of the above cases. You mayalso use C<print ref($object)> to find out the class C<$object> wasblessed into.Another possible reason for problems is because you've used theindirect object syntax (eg, C<find Guru "Samy">) on a class namebefore Perl has seen that such a package exists. It's wisest to makesure your packages are all defined before you start using them, whichwill be taken care of if you use the C<use> statement instead ofC<require>. If not, make sure to use arrow notation (eg.,C<< Guru->find("Samy") >>) instead. Object notation is explained inL<perlobj>.Make sure to read about creating modules in L<perlmod> andthe perils of indirect objects in L<perlobj/"Method Invocation">.=head2 How can I find out my current package?If you're just a random program, you can do this to findout what the currently compiled package is: my $packname = __PACKAGE__;But, if you're a method and you want to print an error messagethat includes the kind of object you were called on (which isnot necessarily the same as the one in which you were compiled): sub amethod { my $self = shift; my $class = ref($self) || $self; warn "called me from a $class object"; }=head2 How can I comment out a large block of perl code?You can use embedded POD to discard it. Enclose the blocks you wantto comment out in POD markers. The <=begin> directive marks a sectionfor a specific formatter. Use the C<comment> format, which no formattershould claim to understand (by policy). Mark the end of the blockwith <=end>. # program is here =begin comment all of this stuff here will be ignored by everyone =end comment =cut # program continuesThe pod directives cannot go just anywhere. You must put apod directive where the parser is expecting a new statement,not just in the middle of an expression or some otherarbitrary grammar production.See L<perlpod> for more details.=head2 How do I clear a package?Use this code, provided by Mark-Jason Dominus: sub scrub_package { no strict 'refs'; my $pack = shift; die "Shouldn't delete main package" if $pack eq "" || $pack eq "main"; my $stash = *{$pack . '::'}{HASH}; my $name; foreach $name (keys %$stash) { my $fullname = $pack . '::' . $name; # Get rid of everything with that name. undef $$fullname; undef @$fullname; undef %$fullname; undef &$fullname; undef *$fullname; } }Or, if you're using a recent release of Perl, you canjust use the Symbol::delete_package() function instead.=head2 How can I use a variable as a variable name?Beginners often think they want to have a variable contain the nameof a variable. $fred = 23; $varname = "fred"; ++$$varname; # $fred now 24This works I<sometimes>, but it is a very bad idea for two reasons.The first reason is that this technique I<only works on globalvariables>. That means that if $fred is a lexical variable createdwith my() in the above example, the code wouldn't work at all: you'daccidentally access the global and skip right over the private lexicalaltogether. Global variables are bad because they can easily collideaccidentally and in general make for non-scalable and confusing code.Symbolic references are forbidden under the C<use strict> pragma.They are not true references and consequently are not reference countedor garbage collected.The other reason why using a variable to hold the name of anothervariable is a bad idea is that the question often stems from a lack ofunderstanding of Perl data structures, particularly hashes. By usingsymbolic references, you are just using the package's symbol-table hash(like C<%main::>) instead of a user-defined hash. The solution is touse your own hash or a real reference instead. $USER_VARS{"fred"} = 23; $varname = "fred"; $USER_VARS{$varname}++; # not $$varname++There we're using the %USER_VARS hash instead of symbolic references.Sometimes this comes up in reading strings from the user with variablereferences and wanting to expand them to the values of your perlprogram's variables. This is also a bad idea because it conflates theprogram-addressable namespace and the user-addressable one. Instead ofreading a string and expanding it to the actual contents of your program'sown variables: $str = 'this has a $fred and $barney in it'; $str =~ s/(\$\w+)/$1/eeg; # need double evalit would be better to keep a hash around like %USER_VARS and havevariable references actually refer to entries in that hash: $str =~ s/\$(\w+)/$USER_VARS{$1}/g; # no /e here at allThat's faster, cleaner, and safer than the previous approach. Of course,you don't need to use a dollar sign. You could use your own scheme tomake it less confusing, like bracketed percent symbols, etc. $str = 'this has a %fred% and %barney% in it'; $str =~ s/%(\w+)%/$USER_VARS{$1}/g; # no /e here at allAnother reason that folks sometimes think they want a variable tocontain the name of a variable is because they don't know how to buildproper data structures using hashes. For example, let's say theywanted two hashes in their program: %fred and %barney, and that theywanted to use another scalar variable to refer to those by name. $name = "fred"; $$name{WIFE} = "wilma"; # set %fred $name = "barney"; $$name{WIFE} = "betty"; # set %barneyThis is still a symbolic reference, and is still saddled with theproblems enumerated above. It would be far better to write: $folks{"fred"}{WIFE} = "wilma"; $folks{"barney"}{WIFE} = "betty";And just use a multilevel hash to start with.The only times that you absolutely I<must> use symbolic references arewhen you really must refer to the symbol table. This may be because it'ssomething that can't take a real reference to, such as a format name.Doing so may also be important for method calls, since these always gothrough the symbol table for resolution.In those cases, you would turn off C<strict 'refs'> temporarily so youcan play around with the symbol table. For example: @colors = qw(red blue green yellow orange purple violet); for my $name (@colors) { no strict 'refs'; # renege for the block *$name = sub { "<FONT COLOR='$name'>@_</FONT>" }; }All those functions (red(), blue(), green(), etc.) appear to be separate,but the real code in the closure actually was compiled only once.So, sometimes you might want to use symbolic references to directlymanipulate the symbol table. This doesn't matter for formats, handles, andsubroutines, because they are always global--you can't use my() on them.For scalars, arrays, and hashes, though--and usually for subroutines--you probably only want to use hard references.=head2 What does "bad interpreter" mean?(contributed by brian d foy)The "bad interpreter" message comes from the shell, not perl. Theactual message may vary depending on your platform, shell, and localesettings.If you see "bad interpreter - no such file or directory", the firstline in your perl script (the "shebang" line) does not contain theright path to perl (or any other program capable of running scripts).Sometimes this happens when you move the script from one machine toanother and each machine has a different path to perl--/usr/bin/perlversus /usr/local/bin/perl for instance. It may also indicatethat the source machine has CRLF line terminators and thedestination machine has LF only: the shell tries to find/usr/bin/perl<CR>, but can't.If you see "bad interpreter: Permission denied", you need to make yourscript executable.In either case, you should still be able to run the scripts with perlexplicitly: % perl script.plIf you get a message like "perl: command not found", perl is not inyour PATH, which might also mean that the location of perl is notwhere you expect it so you need to adjust your shebang line.=head1 REVISIONRevision: $Revision: 10100 $Date: $Date: 2007-10-21 20:59:30 +0200 (Sun, 21 Oct 2007) $See L<perlfaq> for source control details and availability.=head1 AUTHOR AND COPYRIGHTCopyright (c) 1997-2007 Tom Christiansen, Nathan Torkington, andother authors as noted. All rights reserved.This documentation is free; you can redistribute it and/or modify itunder the same terms as Perl itself.Irrespective of its distribution, all code examples in this fileare hereby placed into the public domain. You are permitted andencouraged to use this code in your own programs for funor for profit as you see fit. A simple comment in the code givingcredit would be courteous but is not required.
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?