[prog] speaking Perlish

Jacinta Richardson jarich at perltraining.com.au
Sun Oct 27 18:53:47 EST 2002


Some great points Meryll.  Just wanted to add a few extra things.

> use strict;  # this is considered a good programming practice.

Most definately!

> chomp (my $sleep = <stdin>);
> my $hours = 365*$sleep;

If $sleep is any of the following, $hours will equal 0:
" 6 hours"	( note leading space )
""		( empty string (they just hit newline)
"six hours"	( no digit characters )

etc.

If $sleep is something like "8" or "8 hours" or even "8 fooblewhatsits"
then $hours will be 2120 which will be what you want.  Likewise if $sleep
is "7.5" or "7.5 hours" etc then $hours will be 2737.5 appropriately.
Note that $sleep = "7 1/2" is the same as $sleep = 7 in this calculation.

What is happening here, is that when Perl takes a string and treats it as
a number it takes as many digits as possible from the start of the line
and terminates at the first non valid number character.  Hence
"5.6.5" becomes 5.6
" 5.6"  becomes 0 (no leading digits so it becomes "" which is treated as 0)
"5 hours" becomes 5 and
"5hours" also becomes 5
".2"	  becomes 0.2
etc

> #  print "\nAnd how long do you expect to live? ";
> #  This question invites the user to write a number and then
> #  the word "years" after it.  But you haven't done any data
> #  validation and are clearly doing only numerical calculation
> 
> print "\nAnd how many years do you expect to live? ";
> chomp (my $live = <stdin>);
> 
> # data validation using Regex
> $live =~ s/\D*//g;  # strip off all non-digits

With an understanding of how Perl converts numbers you may understand why
it is that your test cases worked fine.  Data validation, however, is a
great idea.  Note, though, that the above prevents floating point values.
This is because \D is the same as [^0-9] and . is not in 0-9.  An
alternative regexp would be:
$live =~ s/[^0-9.]//g;    


> if (!$live) {  # make sure there is a number in there.
>     print "Please answer numerically.  Quitting.\n";
>     exit 1;
> }

I prefer unless myself.  ;)
unless($live) {
    print ".....";
    exit 1;
}

Great job Kenny.

	Jacinta





More information about the Programming mailing list