📄 perlintro.pod
字号:
conditional blocks more English like: # the traditional way if ($zippy) { print "Yow!"; } # the Perlish post-condition way print "Yow!" if $zippy; print "We have no bananas" unless $bananas;=item while while ( condition ) { ... }There's also a negated version, for the same reason we have C<unless>: until ( condition ) { ... }You can also use C<while> in a post-condition: print "LA LA LA\n" while 1; # loops forever=item forExactly like C: for ($i = 0; $i <= $max; $i++) { ... }The C style for loop is rarely needed in Perl since Perl providesthe more friendly list scanning C<foreach> loop.=item foreach foreach (@array) { print "This element is $_\n"; } print $list[$_] foreach 0 .. $max; # you don't have to use the default $_ either... foreach my $key (keys %hash) { print "The value of $key is $hash{$key}\n"; }=backFor more detail on looping constructs (and some that weren't mentioned inthis overview) see L<perlsyn>.=head2 Builtin operators and functionsPerl comes with a wide selection of builtin functions. Some of the oneswe've already seen include C<print>, C<sort> and C<reverse>. A list ofthem is given at the start of L<perlfunc> and you can easily readabout any given function by using C<perldoc -f I<functionname>>.Perl operators are documented in full in L<perlop>, but here are a fewof the most common ones:=over 4=item Arithmetic + addition - subtraction * multiplication / division=item Numeric comparison == equality != inequality < less than > greater than <= less than or equal >= greater than or equal=item String comparison eq equality ne inequality lt less than gt greater than le less than or equal ge greater than or equal(Why do we have separate numeric and string comparisons? Because we don'thave special variable types, and Perl needs to know whether to sortnumerically (where 99 is less than 100) or alphabetically (where 100 comesbefore 99).=item Boolean logic && and || or ! not(C<and>, C<or> and C<not> aren't just in the above table as descriptionsof the operators -- they're also supported as operators in their ownright. They're more readable than the C-style operators, but havedifferent precedence to C<&&> and friends. Check L<perlop> for moredetail.)=item Miscellaneous = assignment . string concatenation x string multiplication .. range operator (creates a list of numbers)=backMany operators can be combined with a C<=> as follows: $a += 1; # same as $a = $a + 1 $a -= 1; # same as $a = $a - 1 $a .= "\n"; # same as $a = $a . "\n";=head2 Files and I/OYou can open a file for input or output using the C<open()> function.It's documented in extravagant detail in L<perlfunc> and L<perlopentut>,but in short: open(my $in, "<", "input.txt") or die "Can't open input.txt: $!"; open(my $out, ">", "output.txt") or die "Can't open output.txt: $!"; open(my $log, ">>", "my.log") or die "Can't open my.log: $!";You can read from an open filehandle using the C<< <> >> operator. Inscalar context it reads a single line from the filehandle, and in listcontext it reads the whole file in, assigning each line to an element ofthe list: my $line = <$in>; my @lines = <$in>;Reading in the whole file at one time is called slurping. It canbe useful but it may be a memory hog. Most text file processingcan be done a line at a time with Perl's looping constructs.The C<< <> >> operator is most often seen in a C<while> loop: while (<$in>) { # assigns each line in turn to $_ print "Just read in this line: $_"; }We've already seen how to print to standard output using C<print()>.However, C<print()> can also take an optional first argument specifyingwhich filehandle to print to: print STDERR "This is your final warning.\n"; print $out $record; print $log $logmessage;When you're done with your filehandles, you should C<close()> them(though to be honest, Perl will clean up after you if you forget): close $in or die "$in: $!";=head2 Regular expressionsPerl's regular expression support is both broad and deep, and is thesubject of lengthy documentation in L<perlrequick>, L<perlretut>, andelsewhere. However, in short:=over 4=item Simple matching if (/foo/) { ... } # true if $_ contains "foo" if ($a =~ /foo/) { ... } # true if $a contains "foo"The C<//> matching operator is documented in L<perlop>. It operates onC<$_> by default, or can be bound to another variable using the C<=~>binding operator (also documented in L<perlop>).=item Simple substitution s/foo/bar/; # replaces foo with bar in $_ $a =~ s/foo/bar/; # replaces foo with bar in $a $a =~ s/foo/bar/g; # replaces ALL INSTANCES of foo with bar in $aThe C<s///> substitution operator is documented in L<perlop>.=item More complex regular expressionsYou don't just have to match on fixed strings. In fact, you can matchon just about anything you could dream of by using more complex regularexpressions. These are documented at great length in L<perlre>, but forthe meantime, here's a quick cheat sheet: . a single character \s a whitespace character (space, tab, newline, ...) \S non-whitespace character \d a digit (0-9) \D a non-digit \w a word character (a-z, A-Z, 0-9, _) \W a non-word character [aeiou] matches a single character in the given set [^aeiou] matches a single character outside the given set (foo|bar|baz) matches any of the alternatives specified ^ start of string $ end of stringQuantifiers can be used to specify how many of the previous thing youwant to match on, where "thing" means either a literal character, oneof the metacharacters listed above, or a group of characters ormetacharacters in parentheses. * zero or more of the previous thing + one or more of the previous thing ? zero or one of the previous thing {3} matches exactly 3 of the previous thing {3,6} matches between 3 and 6 of the previous thing {3,} matches 3 or more of the previous thingSome brief examples: /^\d+/ string starts with one or more digits /^$/ nothing in the string (start and end are adjacent) /(\d\s){3}/ a three digits, each followed by a whitespace character (eg "3 4 5 ") /(a.)+/ matches a string in which every odd-numbered letter is a (eg "abacadaf") # This loop reads from STDIN, and prints non-blank lines: while (<>) { next if /^$/; print; }=item Parentheses for capturingAs well as grouping, parentheses serve a second purpose. They can beused to capture the results of parts of the regexp match for later use.The results end up in C<$1>, C<$2> and so on. # a cheap and nasty way to break an email address up into parts if ($email =~ /([^@]+)@(.+)/) { print "Username is $1\n"; print "Hostname is $2\n"; }=item Other regexp featuresPerl regexps also support backreferences, lookaheads, and all kinds ofother complex details. Read all about them in L<perlrequick>,L<perlretut>, and L<perlre>.=back=head2 Writing subroutinesWriting subroutines is easy: sub logger { my $logmessage = shift; open my $logfile, ">>", "my.log" or die "Could not open my.log: $!"; print $logfile $logmessage; }Now we can use the subroutine just as any other built-in function: logger("We have a logger subroutine!");What's that C<shift>? Well, the arguments to a subroutine are availableto us as a special array called C<@_> (see L<perlvar> for more on that).The default argument to the C<shift> function just happens to be C<@_>.So C<my $logmessage = shift;> shifts the first item off the list ofarguments and assigns it to C<$logmessage>.We can manipulate C<@_> in other ways too: my ($logmessage, $priority) = @_; # common my $logmessage = $_[0]; # uncommon, and uglySubroutines can also return values: sub square { my $num = shift; my $result = $num * $num; return $result; }Then use it like: $sq = square(8);For more information on writing subroutines, see L<perlsub>.=head2 OO PerlOO Perl is relatively simple and is implemented using references whichknow what sort of object they are based on Perl's concept of packages.However, OO Perl is largely beyond the scope of this document.Read L<perlboot>, L<perltoot>, L<perltooc> and L<perlobj>.As a beginning Perl programmer, your most common use of OO Perl will bein using third-party modules, which are documented below.=head2 Using Perl modulesPerl modules provide a range of features to help you avoid reinventingthe wheel, and can be downloaded from CPAN ( http://www.cpan.org/ ). Anumber of popular modules are included with the Perl distributionitself.Categories of modules range from text manipulation to network protocolsto database integration to graphics. A categorized list of modules isalso available from CPAN.To learn how to install modules you download from CPAN, readL<perlmodinstall>To learn how to use a particular module, use C<perldoc I<Module::Name>>.Typically you will want to C<use I<Module::Name>>, which will then giveyou access to exported functions or an OO interface to the module.L<perlfaq> contains questions and answers related to many commontasks, and often provides suggestions for good CPAN modules to use.L<perlmod> describes Perl modules in general. L<perlmodlib> lists themodules which came with your Perl installation.If you feel the urge to write Perl modules, L<perlnewmod> will give yougood advice.=head1 AUTHORKirrily "Skud" Robert <skud@cpan.org>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -