- 论坛徽章:
- 0
|
第一题吧:
Write a Perl program P1.pl to greet whatever is passed to it on the command line,
e.g.,
Hello, stranger!
There can be a problem with the above script: a parameter must be supplied, otherwise we'll get an error message.
comp315@turing> ./P1.pl
Use of uninitialized value $thing in concatenation (.)
or string at ./P1.pl line 4.
Hello, !
You should write the script in such a way that it will print a default value, let's say
\world", if no value is supplied on the command line.
comp315@turing> ./P1.pl
Hello, world!
Pay attention when providing zero as a parameter, as the greeting should be
comp315@turing> ./P1.pl 0
Hello, 0!
Modify the script to say \Goodbye" according to whether the -b switch was used on
the command line and the corresponding comment will be the output:
>P1.pl # Hello, world!
>P1.pl student # Hello, student!
>P1.pl -b # Goodbye, world!
>P1.pl -b 'nice student' # Goodbye, nice student!
第二题吧, 改错这个我没怎么看懂有谁能帮我看看咩
The following program is supposed to read text from standard input and to output
them sorted by length. The lines are read in an array called @lines. Based on
@lines, a new array @sortarray is created such that each element of this array is the
length of a line of text, concatenated with the vertical bar `|' character, concatenated
with the index of that line of text in the original array @lines. The program sorts
the new array, and then uses the results to display the original lines in sorted order.
#!/usr/bin/perl
use strict;
use warnings;
my @lines;
my @sortarray;
# read in the entire input
@lines = <STDIN>;
#construct the array with the length prepended
foreach (0 .. $#lines) {
$sortarray[$_] = length($lines[$_]) . "|" . $_;
}
# sort using numeric comparison
@sortarray = sort { $a <=> $b } @sortarray;
# display results
print "****************************************\n";
foreach (@sortarray) {
print $lines[substr($_, index($_, "|"))];
}
|
|