### G ### 12/05 小考 G 參考解答 1. perl -ne 'print "$1\n" if /(\d+\s+Pages)/' astrobooks.htm 2. perl -ne 'print "$1\n" if /\b([A-Z][a-z][a-z]-\d\d)\b/' astrobooks.htm 3. perl -ne 'print "$1\n" if /\bby\s+.*?([-\w]+),/' astrobooks.htm 4. perl -ne 'print "$1\n" if /(\$\d+\.\d+)/' astrobooks.htm 5. perl -ne 'print "$1\n" if m#ASIN/(\d+\w?)/sbsoftware#' astrobooks.htm 6. perl -ne 'print "$1\n" if /img\s+src="(.*?)"/' astrobooks.htm 7. perl -ne 'print "$1\n" if /font size=\+1>(.*?)) { my (undef, undef, $size, $date, $time, $fn) = split " "; next unless $fn =~ /\.(\w+)$/; my ($ext) = $1; if (not defined $newest_file{$ext} or $newest_date{$ext} lt $date or $newest_date{$ext} eq $date and $newest_time{$ext} lt $time) { $newest_file{$ext} = $fn; $newest_date{$ext} = $date; $newest_time{$ext} = $time; } } my ($ext); foreach $ext (sort keys %newest_file) { printf "$newest_date{$ext} $newest_time{$ext} $newest_file{$ext}\n"; } ### E ### 11/12 小考 E 參考解答 #!/usr/bin/perl -w use strict; my (%by_year, %by_ext); while () { my ($length, $method, undef, undef, $date, undef, undef, $name) = split " "; next unless defined $name and $length =~ /^\d+$/; next if $method eq 'Stored'; (undef, undef, $date) = split /-/, $date; $by_year{$date} += $length; my (@f) = split /\./, $name; next if $#f <= 0; my ($ext) = $f[$#f]; next if $ext =~ /\//; $by_ext{$ext} += $length; } my ($k); foreach $k (sort keys %by_year) { printf "%8d %-1s\n", $by_year{$k}, $k; } print "\n"; foreach $k (sort keys %by_ext) { printf "%8d %-1s\n", $by_ext{$k}, $k; } ### D ### 11/5 小考 D 參考解答 #!/usr/bin/perl -w use strict; my (%size, $stored, $stored_png, $k); while () { my (@f) = split " "; if ($f[1] eq "Stored") { ++$stored; ++$stored_png if $f[7] =~ /\.png$/; } next unless /\.shtml$/; my (@path) = split /\//, $f[7]; $size{$path[1]} += $f[2] if $#path >= 2; } print "$stored stored files ($stored_png png, ", $stored-$stored_png, " others)\n\n"; foreach $k (sort keys %size) { printf "%6d $k\n", $size{$k}; } ### C ### 10/29 小考 C 參考解答 #!/usr/bin/perl -w use strict; my (%total); while () { my ($dura, $day, $user) = split " ", $_; if ($ARGV[0] eq "day") { if ($ARGV[1] eq "count") { ++$total{$day}; } else { $total{$day} += $dura; } } else { if ($ARGV[1] eq "count") { ++$total{$user}; } else { $total{$user} += $dura; } } } my ($k); foreach $k (sort keys %total) { printf "%-8s %8d\n", $k, $total{$k}; } ### B ### 10/22 小考 B 參考解答 #!/usr/bin/perl -w use strict; my ($i, $x, $c); while () { for ($i=0; $i= 0) { $n = $ARGV[0]; if ($#ARGV >= 2) { ($small, $large) = ($ARGV[1], $ARGV[2]); } } my ($t); print "$small $large"; while ($n > 2) { $t = $large; $large += $small; $small = $t; print " $large"; --$n; } print "\n"; ### end ###