On Tue, Oct 21, 2008 at 08:49, birdinforest <[EMAIL PROTECTED]> wrote:
> I am a student and enrolled Unix programing this semester.
> There are two questions relating to perl  I can not work out in the
> last exam ( Actually I have write out my code, however the exam system
> marked it as "wrong"). Please help me to point out the fault. Thanks.
>
> QUESTION 1
> Write a perl script called perl_has_number.pl which takes one
> argument
> which is any string. The script should output "true" if the string
> contains any digits, and "false" otherwise.
>
> MY CODE:
> #!/usr/bin/perl -w
> if ($ARGV[0]=~ /\d+/)
> {
>  print "true\n";
> }
> else
> {
>  print "false\n";
> }
snip

Things an automated system may find wrong:
1. the spec says to print "true" or "false" and you are printing
"true\n" or "false\n"
2. the spec says that the script should receive only one argument, but
your script will process the first argument if more than on is given
3. you are using \d which in modern (5.8 and above, possibly some 5.6
versions) Perl matches non-English number characters as well (e.g.
Mongolian five: "\x{1815}")
4. the interpreter may not be in /usr/bin

Additional things I find wrong with it:
1. you aren't using strict
2. you are using -w to turn on warnings instead of the warnings pragma or $^W=1
3. the bracing style is horrible

snip
> QUESTION 2
> Write a perl script called perl_digits.pl which takes any number of
> arguments. The script should return the number found by deleting all
> non-digits.
>
> Example:
>
> "./perl_digits.pl and1 pan2d 30rr and 4"
>
> will return 12304
>
> MY CODE:
> #!/usr/bin/perl -w
> sub outcom
> {
>  $outcome="";
>    foreach $a (@ARGV)
>      {
>        if ($a=~/\d+/)
>        {
>          $outcome=$outcome.$&;
>        }
>      }
>    return $outcome;
> }
>
> $digital=outcom(@ARGV);
> print $digital . "\n";
snip

Many of the earlier statements hold true for this one as well, but the
error is probably on this case:

./perl_digits.pl and1 pan2d 3rr4 and 5

which should print out

12345

but instead prints out

1235

Things I find wrong:
1. everything I said before
2. you are passing @ARGV to the function, but aren't using @_ in the
function (instead you go back to @ARGV)
3. you misspelled outcome which is a very bad named for the function
to start with
4. you are using $a which has special meaning to the sort function
5. you are using $& instead of a capture (thereby slowing down all regexes)
6. you are using a loop where you should be using a core function
7. you are spelling for as foreach (those extra four letters don't do
anything and are being dropped in Perl 6)
8. you are spacing the assignments as if it were a shell script

-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to