perlfaq7.pod
来自「MSYS在windows下模拟了一个类unix的终端」· POD 代码 · 共 975 行 · 第 1/3 页
POD
975 行
or via a forward reference or C<use subs> declaration. Even in thiscase, you get a clean @_ without any of the old values leaking throughwhere they don't belong.=head2 How do I create a switch or case statement?This is explained in more depth in the L<perlsyn>. Briefly, there'sno official case statement, because of the variety of tests possiblein Perl (numeric comparison, string comparison, glob comparison,regex matching, overloaded comparisons, ...). Larry couldn't decidehow best to do this, so he left it out, even though it's been on thewish list since perl1.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, thistime lined up in a way to make it look more like a switch statement.We'll do a multi-way 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 C<perlsyn/"Basic BLOCKs and Switch Statements"> for many 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"; } =head2 How can I catch accesses to undefined variables/functions/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<-w>, you can use a handler to trap the pseudo-signalC<__WARN__> like this: $SIG{__WARN__} = sub { for ( $_[0] ) { # voici un switch statement /Use of uninitialized value/ && do { # promote warning to a fatal die $_; }; # other warning cases to catch could go here; warn $_; } };=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/"WARNING">.=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?Use embedded POD to discard it: # program is here =for nobody This paragraph is commented out # program continues =begin comment text all of this stuff here will be ignored by everyone =end comment text =cutThis can't go just anywhere. You have to put a pod directive wherethe parser is expecting a new statement, not just in the middleof an expression or some other arbitrary yacc grammar production.=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 can just 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. $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.=head1 AUTHOR AND COPYRIGHTCopyright (c) 1997-1999 Tom Christiansen and Nathan Torkington.All rights reserved.When included as part of the Standard Version of Perl, or as part ofits complete documentation whether printed or otherwise, this workmay be distributed only under the terms of Perl's Artistic License.Any distribution of this file or derivatives thereof I<outside>of that package require that special arrangements be made withcopyright holder.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 + -
显示快捷键?