复制代码
- use utf8;
- use Encode;
- use IO::Handle;
- STDOUT->autoflush(1);
- my $file = encode('gbk', "Perl进阶-基础.md");
- open my $fh, "<:utf8", $file or die "$!";
- my %lang_fmt = (
- 'perl' => 'pl',
- 'python' => 'py',
- 'c' => 'c',
- 'cpp' => 'cpp',
- 'ruby' => 'rb',
- );
- my @topics;
- my $lang;
- my $indent = 0;
- while ( my $line = <$fh> )
- {
- #代码块
- if ($line=~/\`{3}(\w+)$/)
- {
- $lang = lc($1);
- $line=~s/\`{3}(\w+)/\[code\]/;
- $line=~s/perl/bash/;
- }
- elsif ($line=~/\`{3}$/) #inline code
- {
- $line=~s/\`{3}\r?\n$/\[\/code\]/;
- }
- elsif ($line=~/^\s*#[^#]/) #一级标题
- {
- $line=~s/^\s*#(.*)$/\[b\]\[size=5\]$1\[\/size\]\[\/b\]\n\[list\]\[list\]/;
- $line = "[/list]"x2 . "\n".$line if ($indent == 1);
- $line = "[/list]"x4 ."\n".$line if ($indent == 2);
- $indent = 1;
- }
- elsif ($line=~/^\s*##[^#]/) #二级标题
- {
- $line=~/^\s*##(.*)$/;
- $line=~s/^\s*##(.*)$/\[b\]$1\[\/b\]\n\[list\]\[list\]/;
- $line = "[/list]"x2 ."\n".$line if ($indent >= 2);
- $indent = 2;
- }
- elsif ($line=~/\*{2}[^*]/) #粗体 (原文书写同一段文字最好不要断行)
- {
- $line=~s/\*{2}(.*)\*{2}/\[b\]$1\[\/b\]/;
- }
- elsif ($line=~/\*[^*]/) #倾体 (原文书写同一段文字最好不要断行)
- {
- $line=~s/\*(.*)\*/\[i\]$1\[\/i\]/;
- }
- $line=~s/\s*`(.*)`\s*$/\[code\]$1\[\/code\]\n/;
- push @topics, $line;
- }
- my $all = join("", @topics);
- $all =~s/(\r?\n)+$//;
- if ( $all=~/\[list\]/ )
- {
- $all .= '[/list]';
- }
- print encode('gbk', $all);
- print "\n";
- close $fh;
结果为 16, 32, 64复制代码
- my @input_numbers = (1, 2, 4, 8, 16, 32, 64);
- my @bigger_than_10 = grep $_ > 10, @input_numbers;
如果测试表达式较为复杂,可以写在一个子例程中,然后通过 grep 调用。复制代码
- my @end_in_4 = grep /4$/, @input_numbers;
块形式(相比调用子例程的形式,少了 return。在这里使用 return 将退出 grep ):复制代码
- my @odd_digit_sum = grep digit_sum_is_odd($_), @input_numbers;
- sub digit_sum_is_odd {
- my $input = shift;
- my @digits = split //, $input; # Assume no nondigit characters
- my $sum;
- $sum += $_ for @digits;
- return $sum % 2;
- }
复制代码
- my @odd_digit_sum = grep {
- my $sum;
- $sum += $_ for split //;
- $sum % 2;
- } @input_numbers;
以及 map 没有规定对于每一项只返回一个值复制代码
- my @input_numbers = (1, 2, 4, 8, 16, 32, 64);
- my @result = map $_ + 100, @input_numbers;
借此可以快速从一个列表生成一组哈希映射,以便于做字典判断复制代码
- my @result = map { $_, 3 * $_ } @input_numbers;
复制代码
- my %hash = map { $_, 1 } @castaways;
- my $person = 'Gilligan';
- if( $hash{$person} ) {
- print "$person is a castaway.\n";
- }
其中每一行都有可能出错导致程序崩溃,但在实际应用中并不意味着应该结束整个程序,Perl 通过 eval 实现错误捕获:复制代码
- my $average = $total / $count; # divide by zero?
- print "okay\n" unless /$match/; # illegal pattern?
- open MINNOW, '>', 'ship.txt'
- or die "Can't create 'ship.txt': $!"; # user?defined die?
- implement($_) foreach @rescue_scheme; # die inside sub?
当 eval 代码块运行出错时,错误信息保存到 $@,eval 之后的代码继续运行。注意 eval 不是结构语句,末尾必须加分号。复制代码
- eval { $average = $total / $count } ;
- print "Continuing after error: $@" if $@;
$average 要么是"商"要么是"undef"。复制代码
- my $average = eval { $total / $count };
复制代码
- use Try::Tiny;
- my $average = try { $total / $count } catch { "NaN" };
因为 eval 能够返回最后一句代码的结果,所以不必将赋值放在待执行的字符串中复制代码
- eval '$sum = 2 + 2';
- print "The sum is $sum\n";
和代码块形式一样,如果执行错误,有关信息将保留到 $@:复制代码
- foreach my $operator ( qw(+ ? * /) ) {
- my $result = eval "2 $operator 2";
- print "2 $operator 2 is $result\n";
- }
>The quotient is复制代码
- print 'The quotient is ', eval '5 /', "\n";
- warn $@ if $@;
如果改为 do 语句块的形式,只需要一个 $bowler复制代码
- my $bowler;
- if( ...some condition... ) {
- $bowler = 'Mary Ann';
- }
- elsif( ... some condition ... ) {
- $bowler = 'Ginger';
- }
- else {
- $bowler = 'The Professor';
- }
复制代码
- my $bowler = do {
- if( ... some condition ... ) { 'Mary Ann' }
- elsif( ... some condition ... ) { 'Ginger' }
- else { 'The Professor' }
- };
复制代码
- $filename = __FILE__;
- my $file_contents = do {
- local $/;
- local @ARGV = ( $filename );
- <>;
- };
- print $file_contents;
类似于 `eval "type slurp.pl";` 区别参考 perldoc -f do复制代码
- do "slurp.pl";
use List::Util 的实质是在 BEGIN 块中执行 require 以及 该模块的 import() 方法;复制代码
- require List::Util;
通常 use 使用模块名的形式,而 require 还可以用文件名作为参数,导入文件:复制代码
- BEGIN {
- require List::Util;
- List::Util->import( ... );
- }
require 能够记住已经加载过的文件,对于重复的加载将不会再执行 ( 对比 do )。更多内容参考 12 章 - Creating Your Own Perl Distribution复制代码
- require $filename;
复制代码
- my %total_bytes;
- while (<DATA>) {
- my ($source, $destination, $bytes) = split;
- $total_bytes{$source}{$destination} += $bytes;
- }
- for my $source (sort keys %total_bytes) {
- for my $destination (sort keys %{ $total_bytes{$source} }) {
- print "$source => $destination:",
- " $total_bytes{$source}{$destination} bytes\n";
- }
- print "\n";
- }
- __DATA__
- professor.hut gilligan.crew.hut 1250
- professor.hut lovey.howell.hut 910
- thurston.howell.hut lovey.howell.hut 1250
- professor.hut lovey.howell.hut 450
- ginger.girl.hut professor.hut 1218
- ginger.girl.hut maryann.girl.hut 199
perl -d bytecounts.pl Loading DB routines from perl5db.pl version 1.37 Editor support available. Enter h or 'h h' for help, or 'perldoc perldebug' for more help. main::(bytecounts.pl:1): my %total_bytes; DB<1> s main::(bytecounts.pl:2): while (<DATA>) { DB<1> s main::(bytecounts.pl:3): my ($source, $destination, $bytes) = split; DB<1> s main::(bytecounts.pl:4): $total_bytes{$source}{$destination} += $bytes; DB<1> x $source, $destination, $bytes 0 'professor.hut' 1 'gilligan.crew.hut' 2 1250 |
DB<8> @a = (1 .. 3); DB<9> x @a 0 1 1 2 2 3 |
DB<10> %h = qw/a 1 b 2 c 3/; DB<12> x \%h 0 HASH(0x2ac9e2c) 'a' => 1 'b' => 2 'c' => 3 |
DB<31> %h = qw(a b c d e f); DB<34> x sort keys %h 0 'a' 1 'c' 2 'e' |
DB<24> S main main::BEGIN main::dumpValue main::dumpvar main::test |
复制代码
- use Data::Dumper;
- print Dumper(\%total_bytes);
$VAR1 = { 'thurston.howell.hut' => { 'lovey.howell.hut' => 1250 }, 'ginger.girl.hut' => { 'maryann.girl.hut' => 199, 'professor.hut' => 1218 }, 'professor.hut' => { 'gilligan.crew.hut' => 1250, 'lovey.howell.hut' => 1360 } }; |
复制代码
- use Data::Dumper;
- $Data::Dumper::Purity = 1; # 声明打印的数据可能出现自引用的情况
- my @data1 = qw(one won);
- my @data2 = qw(two too to);
- push @data2, \@data1;
- push @data1, \@data2;
- print Dumper(\@data1, \@data2);
$VAR1 = [ 'one', 'won', [ 'two', 'too', 'to', [] ] ]; $VAR1->[2][3] = $VAR1; $VAR2 = $VAR1->[2]; |
DB<2> x \@data1, \@data2 0 ARRAY(0x24a4e84) 0 'one' 1 'won' 2 ARRAY(0x47f324) 0 'two' 1 'too' 2 'to' 3 ARRAY(0x24a4e84) -> REUSED_ADDRESS 1 ARRAY(0x47f324) -> REUSED_ADDRESS |
复制代码
- use Data::Dump qw(dump);
- dump( \%total_bytes );
{ "ginger.girl.hut" => { "maryann.girl.hut" => 199, "professor.hut" => > 1218 }, "professor.hut" => { "gilligan.crew.hut" => 1250, "lovey.howell.hut" > => 1360 }, "thurston.howell.hut" => { "lovey.howell.hut" => 1250 }, } |
复制代码
- use Data::Printer;
- p( %total_bytes );
{ ginger.girl.hut { maryann.girl.hut 199, professor.hut 1218 }, professor.hut { gilligan.crew.hut 1250, lovey.howell.hut 1360 }, thurston.howell.hut { lovey.howell.hut 1250 } } |
欢迎光临 批处理之家 (http://www.bathome.net/) | Powered by Discuz! 7.2 |