Hatena::Groupperl

Press::Alt_R

2010-04-22

『初めてのPerl』 Cpt 3..5 練習の回答例

| 15:55

source.txt

wilma
pebbles
bamm-bamm
fred
betty
barney
dino

source_numbers.txt

4
3
6
5
2
4
1
3
2
6
1
1

3-1.

#!perl
use strict;
use warnings;

open(my $fh , "<" , "source.txt") || die("cannot open file");
my @names = <$fh>;
close($fh);

print reverse @names;

dino
barney
betty
fred
bamm-bamm
pebbles
wilma

3-2.

#!perl
use strict;
use warnings;

open(my $fh , "<" , "source_numbers.txt") || die("cannot open file");
my @numbers = <$fh>;
close($fh);

my @namelist = qw(fred betty barney dino wilma pebbles bamm-bamm);
foreach my $number(@numbers){
  chomp $number;
  print "no. $number is: ", $namelist[$number-1] , "\n";
}
no. 4 is: dino
no. 3 is: barney
no. 6 is: pebbles
no. 5 is: wilma
no. 2 is: betty
no. 4 is: dino
no. 1 is: fred
no. 3 is: barney
no. 2 is: betty
no. 6 is: pebbles
no. 1 is: fred
no. 1 is: fred

3-3.

#!perl
use strict;
use warnings;

open(my $fh , "<" , "source.txt") || die("cannot open file");
my @names = <$fh>;
close($fh);

print sort {$a cmp $b} @names;
bamm-bamm
barney
betty
dino
fred
pebbles
wilma

4-1.

#!perl
use strict;
use warnings;

my @fred = qw{1 3 5 7 9};
my $fred_total = &total(@fred);
print "the total of \@fred is $fred_total.\n";

my @one_to_thousand = (1..1000);
my $all_total = &total(@one_to_thousand);
print "the total of \@one_to_thousand is $all_total.\n";

sub total{
  my @numbers = @_;
  my $sum = 0;
  foreach my $num(@numbers){
    $sum += $num;
  }
  return $sum;
}
the total of @fred is 25.
the total of @one_to_thousand is 500500.