Hi all,

I'm a bit late for a reply, but thought it would be appropriate to ask Babs
exactly what was required from the perl program.

Did you want to print the number of elements in the array, or print each
element in the array?

As Andrew Brosnan explained, setting a scalar equal to an array name will
result in the scalar containing the number of elements in the array:
eg.
$scalar = (1..5); # $scalar will be given the value of 5.

See my comments below...

Mike.

-----Original Message-----
From: B. Fongo [mailto:[EMAIL PROTECTED]
Sent: Thursday, 04 September, 2003 7:34 PM
To: [EMAIL PROTECTED]; [EMAIL PROTECTED]
Subject: passing an argument to a subroutine


Hello

An argument passed to a subroutine returns wrong value.

Code example:

@x = (1..5);  [Mike: @x = (1,2,3,4,5)]
$x = @x;  [Mike: $x = 5, the number of elements in @x]

showValue ($x);   # or showValue (\$x);  [Mike: pass $x i.e. '5' to the
subroutine]


sub showValue {
  
  my $forwarded = @_;  [Mike: $forwarded = 'array passed' or $forwarded =
(5)]
[Mike: Note, this has set $forwarded equal to the number of elements in
array (5), or 1]
  print $forwarded;  # print ${$forwarded};  [Mike: print $forwarded now
prints '1']

}

In both cases, the script prints out 1.
What is going on here?

Thanks

Babs

[Mike:  If you want the subroutine to print the number of elements in the
array, you need to change the subroutine to:

sub showValue {
  my $forwarded = $_;
  print $forwarded;
}

That way you pass the scalar $x to the subroutine, which equals 5.
Then the subroutine gets the passed parameter and puts it in the $forwarded
scalar varable, then prints the scalar $forwarded as '5'.
]

If you want the values of the array to be printed, i.e. 1 2 3 4 5, then:

1. remove the line [EMAIL PROTECTED];
2. pass the array to the subroutine thus: showValue(@x);
3. You might need to format the printed output to separate values as it will
likely print '12345'.

Hope this helps,
Mike.

Reply via email to