M
Mihail
Hello,
i have spent several hours with very small perl
program and i believe there is something wrong with
perl. Look:
for (1..999)
{
my $i = $_;
$result1 = $result1 + func1($i);
$result2 = $result2 + func2($i);
}
This code contains absolute critical error, but it is
visible only with "use warnings", otherwise perl returns
silently wrong results. To achieve correct results i have
to use:
for (1..999)
{
my $i = $_;
$result1 = $result1 + func1($i);
$i = $_;
$result2 = $result2 + func2($i);
}
O.K. i know unsafety of "$_". But what is wrong with $i? More
interesting. The problem seems to depend on functions used.
I am really confused... Can anybody explain what is wrong.
Regards,
Mihail
----------------------------------------------------------------
#!/usr/bin/perl
use strict;
use warnings;
my $result1 = 0;
my $result2 = 0;
for (1..999)
{
my $i = $_;
$result1 = $result1 + func1($i);
# HERE IS A PROBLEM. $i is undef??????
# and RESULT IS WRONG!!!
#$i = $_; # is a workaround.
$result2 = $result2 + func2($i);
}
print "*** Sum of first sums of digits : $result1\n";
print "*** Sum of last sums of digits : $result2\n";
# TRY TO RENAME func1 <-> func2 below - PROGRAMM BEHAVIOR WILL
# CHANGE. ????????
sub func1
{
my $sum = 0;
do
{
$_[0] =~ m/^(.).?/;
$sum = $sum + $1;
$_[0] =~ s/^.//;
} while ($_[0]);
return $sum;
}
sub func2
{
return $_[0] % 9 if (($_[0] % 9) > 0);
return 9;
}
------------------------------------------------------------
i have spent several hours with very small perl
program and i believe there is something wrong with
perl. Look:
for (1..999)
{
my $i = $_;
$result1 = $result1 + func1($i);
$result2 = $result2 + func2($i);
}
This code contains absolute critical error, but it is
visible only with "use warnings", otherwise perl returns
silently wrong results. To achieve correct results i have
to use:
for (1..999)
{
my $i = $_;
$result1 = $result1 + func1($i);
$i = $_;
$result2 = $result2 + func2($i);
}
O.K. i know unsafety of "$_". But what is wrong with $i? More
interesting. The problem seems to depend on functions used.
I am really confused... Can anybody explain what is wrong.
Regards,
Mihail
----------------------------------------------------------------
#!/usr/bin/perl
use strict;
use warnings;
my $result1 = 0;
my $result2 = 0;
for (1..999)
{
my $i = $_;
$result1 = $result1 + func1($i);
# HERE IS A PROBLEM. $i is undef??????
# and RESULT IS WRONG!!!
#$i = $_; # is a workaround.
$result2 = $result2 + func2($i);
}
print "*** Sum of first sums of digits : $result1\n";
print "*** Sum of last sums of digits : $result2\n";
# TRY TO RENAME func1 <-> func2 below - PROGRAMM BEHAVIOR WILL
# CHANGE. ????????
sub func1
{
my $sum = 0;
do
{
$_[0] =~ m/^(.).?/;
$sum = $sum + $1;
$_[0] =~ s/^.//;
} while ($_[0]);
return $sum;
}
sub func2
{
return $_[0] % 9 if (($_[0] % 9) > 0);
return 9;
}
------------------------------------------------------------