One would believe it fails... it doesn't
It tries to do the right thing. The result in general is unpredictable. (That is, for a beginner).
The snippet is:
#! /usr/local/bin/perl
use strict;
sub print_percentage
{
my ($total, $part) = @_;
if (int($total) != 0){
printf ("It's about %.2f%%\n", $part/$total *100.);
}
else{
print "Bad usage: $total == 0!!! Cannot divide by '$total'.\n"
+;
}
}
print_percentage(100, 50);
print_percentage("oops", 50);
;1
One could write many variations on the theme:
#! /usr/local/bin/perl
use strict;
if ("38" == 38){
print "hit the jackpot!\n";
}
else {
print "hit elsewhere....\n";
}
;1
Why people do this?
People do mistakes, and they are spoiled by getting used to compilers' help. Many who come to Perl from other languages are used to "it doesn't make any sense" compiler's error. Or run-time exceptions.
They are NOT used to the machine "doing the right thing" for them (of course! what do you mean by doing the right thing?)
And that's the problem for beginners.
Solution
Set up your mind not to guess what it'll do. Learn, find out, know.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|