#!/usr/bin/perl
# Fig. 5.6: fig05_06.pl
# Using foreach loops with hashes.
@opinions = qw( what word is being used most in this array is
what this is used what most is is array what
word used is most is array what is this is array
what is is array this is most );
foreach ( @opinions ) {
++$hash{ $_ };
}
# display sorted by key in ascending order
print "Word\tFrequency\n";
print "----\t---------\n";
foreach ( sort keys( %hash ) ) {
print "$_\t", "*" x $hash{ $_ }, "\n";
}
# display sorted by frequency in descending order
print "\nWord\tFrequency\n";
print "----\t---------\n";
foreach ( sort { $hash{ $b } <=> $hash{ $a } } keys( %hash ) ) {
print "$_\t", "*" x $hash{ $_ }, "\n";
}
---------------------------------
输出如下:
Word Frequency
---- ---------
array *****
being *
in *
is ************
most ****
this ****
used ***
what ******
word **
Word Frequency
---- ---------
is ************
what ******
array *****
most ****
this ****
used ***
word **
being *
in *
下面这个程序和上面这个用法一样.
#!/usr/bin/perl
# Fig. 5.5: fig05_05.pl
# Survey data analysis: Determining the mean, median and mode.
@opinions = ( 8, 9, 4, 7, 8, 5, 6, 4, 9, 9,
7, 8, 9, 5, 4, 8, 7, 8, 7, 7,
6, 6, 8, 9, 1, 9, 8, 7, 8, 7,
7, 8, 9, 8, 9, 4, 9, 6, 8, 4,
6, 7, 3, 4, 8, 7, 9, 8, 9, 2 );
# determine the mean
$total = 0;
foreach ( @opinions ) {
$total += $_;
}
$mean = $total / @opinions;
print "Survey mean result: $mean\n";
# determine the median
@sorted = sort { $a <=> $b } @opinions;
$middle = @sorted / 2; # middle element subscript
# for an even number of elements, average the two middle
# elements to determine the median; otherwise, use the
# middle element
if ( @sorted %2 == 0 ) { # even number of elements
$median =
( $sorted[ $middle - 1 ] + $sorted[ $middle ] ) / 2;
}
else { # odd number of elements
$median = $sorted[ $middle ];
}
print "Survey median result: $median\n";
# determine the mode
$mode = 0;
foreach ( @opinions ) {
++$frequency[ $_ ]; # increment the frequency counter
# if the current frequency is greater than the $mode's
# frequency, change $mode to $_
if ( $frequency[ $_ ] > $frequency[ $mode ] ) {
$mode = $_;
}
}
print "Survey mode result: $mode\n\n";
# display a frequency graph
print "Response\tFrequency\n";
print "--------\t---------\n";
foreach ( 1 .. 9 ) {
print "$_\t\t", "*" x $frequency[ $_ ], "\n";
}
---------------------------------------------------------------------
输出如下:
Survey mean result: 6.86
Survey median result: 7
Survey mode result: 8
Response Frequency
-------- ---------
1 *
2 *
3 *
4 ******
5 **
6 *****
7 **********
8 *************
9 ***********
--------------------------------------------------------------------------
摘自: perl编程金典
阅读(1589) | 评论(0) | 转发(0) |