birdinforest 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"; > } > > 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.
Any or all of the following, depending on the examination criteria: - You should use strict; use warnings; instead of using the command line -w switch. - You don't check the number of arguments provided. If there are none at all then your code will throw the warning "Use of uninitialized value in pattern match" and print "false". - You needlessly check for multiple digits, when only one is necessary to fulfil the condition Here is what I would hav written use strict; use warnings; die "Exactly one argument expected" unless @ARGV == 1; my $arg = shift; print $arg =~ /[0-9]/ ? "true\n" : "false\n"; > 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"; > > In my view, both code could give out right results. Could you help me > to find the fault? I would guess that that is just far too complex, and shows that you haven't fully grasped regular expressions yet. You should also know not to use $& $a. Here is my program. use strict; use warnings; print join('', "@ARGV" =~ /[0-9]/g), "\n"; Rob -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/