您的当前位置:首页正文

perl语言入门第九十章作业

2020-03-25 来源:易榕旅网
9.1

Perl 源程序 use strict; use warnings;

my $what = 'fred|barney'; while () { chomp; if (/($what){3}/) { print \"Mached: |$`<$&>$'|\\n\"; } else { print \"No match: |$_|\\n\"; } } 运行结果

9.2

Perl 源程序 use strict; use warnings;

my $in = $ARGV[0]; unless (defined $in) { die \"Usage: $0 filename\"; }

my $out = $in;

$out =~ s/(\\.\\w+)?$/.out/;

unless (open IN, \"<$in\") { die \"Can't open '$in': $!\"; }

unless (open OUT, \">$out\") { die \"Can'twrite '$out': $!\"; }

while () { s/fred/Larry/gi; print OUT $_; } 运行结果

9.3

Perl 源程序 use strict; use warnings;

my $in = $ARGV[0]; unless (defined $in) { die \"Usage: $0 filename\"; }

my $out = $in;

$out =~ s/(\\.\\w+)?$/.out/;

unless (open IN, \"<$in\") { die \"Can't open '$in': $!\"; }

unless (open OUT, \">$out\") { die \"Can'twrite '$out': $!\"; }

while () { chomp; s/fred/\\n/gi; s/Wilma/fred/gi; s/\\n/Wilma/g; print OUT \"$_\\n\";

} 运行结果

9.4

Perl 源程序 use strict; use warnings;

$^I = \".bak\"; while (<>) { if (/^use warnings;/) { $_.= \"## Copyright (C) 20XX by Yours Truly\\n\"; } print; } 运行结果

9.5

Perl 源程序 use strict; use warnings;

my %do_these; foreach (@ARGV) { $do_these{$_} = 1; }

while (<>) { if (/^## Copyright/) { delete $do_these{$ARGV}; } }

@ARGV = sort keys %do_these; $^I = \".bak\"; while (<>) { if (/^use warnings;/) { $_ .= \"## Copyright (C) 20XX by Yours Truly\\n\";

} print; }

运行结果

10.1

Perl 源程序 use strict; use warnings;

my $secret = int(1 + rand 100);

#print \"Don't tell anyone, but the secret number is $secret.\\n\";

while (1) { print \"Please enter a guess from 1 to 100: \"; chomp(my $guess = ); if ($guess =~ /quit|exit|^\\s*$/i) { print \"Sorry you gave up. The number was $secret.\\n\"; last; } elsif ($guess < $secret) { print \"Too small. Try again!\\n\"; } elsif ($guess == $secret) { print \"That was it!\\n\"; last; } else {print \"Too large. Try again!\\n\"; } }

运行结果

10.2

Perl 源程序 use strict; use warnings; use 5.010;

my $Debug = $ENV{DEBUG} // 1; my $secret = int(1 + rand 100);

print \"Don't tell anyone, but the secret number is $secret.\\n\" if $Debug;

while (1) { print \"Please enter a guess from 1 to 100: \"; chomp(my $guess = ); if ($guess =~ /quit|exit|^\\s*$/i) { print \"Sorry you gave up. The number was $secret.\\n\"; last; } elsif ($guess < $secret) { print \"Too small. Try again!\\n\"; } elsif ($guess == $secret) { print \"That was it!\\n\"; last; } else {print \"Too large. Try again!\\n\"; } }

运行结果

10.3

Perl 源程序 use strict; use warnings; use 5.010;

$ENV{ZERO} = 0; $ENV{EMPTY} = '';

$ENV{UNDEFINED} = undef;

my $longest = 0;

foreach my $key (keys %ENV) { my $key_length = length($key); $longest = $key_length if $key_length>$longest; }

foreach my $key (sort keys %ENV ) { printf \"%-${longest}s %s\\n\} 运行结果

因篇幅问题不能全部显示,请点此查看更多更全内容