itshardtogetone wrote:
Hi,
Hello,
Looking at the script below, can someone explain why the final output
is "Final = 1" instead of "Final = 5".
I thought at the end of the while loop, $a_ctr is 5, this value is
then read by the sub module &data() and this value of 5 is then passed
on to sub publish before its being printed out. Thanks
#!/usr/bin/perl
use strict;
use warnings;
{
my $a_ctr = 0;
sub data {
$a_ctr = @_;
When you use an array in scalar context, like above, the array returns
the number of elements in the array and since you passed a single scalar
to this subroutine the number 1 is assigned to $a_ctr. You need to
either assign the contents of the array to a list:
( $a_ctr ) = @_;
or just assign the first element of the array:
$a_ctr = $_[ 0 ];
or use shift() to remove the first element and assign it:
$a_ctr = shift;
}
sub publish{
print "Final = $a_ctr\n";
}
}
#########################
my $a = 5;
my $a_ctr = 0;
while ($a_ctr < $a){
$a_ctr ++;
Usually written as:
foreach my $a_ctr ( 1 .. 5 ) {
print "a_ctr = $a_ctr\n";
&data($a_ctr);
}
&publish();
Unless you are still using Perl version 4 (OMG!!) then you should omit
the ampersand from the beginning of the subroutine call.
John
--
Those people who think they know everything are a great
annoyance to those of us who do. -- Isaac Asimov
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/