0

I have following command, and I put variables "$bus" and "$value" in sub busbitFill.

And the sub can eat $bus successfully, but $value is not working. Please tell me where I was wrong....

....some code that generate $index, $bus and $value...


 print "index=$index\n bus=$bus\n value=$value\n";    #<=all variable printed successfully

 &busbitFill($bus, @array0, $value);                  
                                                         

sub busbitFill {
    my($bus, @array, $val) = @_;
    print "val1: $val\n";                    #<=but when $value goes into sub "busbitFill"
}                                            #  the sub cannot print $val 



<This is the printed result for first row in above code>
index=AA[0]
 
bus=[2:0]

value=110
blueFish
  • 69
  • 3
  • 2
    Don't use `&` in sub calls. It's a special form of a sub call that does something special that you have no reason to do. – ikegami Jun 03 '22 at 06:25

1 Answers1

3

You can't pass arrays to subs, just scalars.

$bus, @array0, $value

is the same as

$bus, $array0[0], $array0[1], ..., , $array0[$#array], $value

So now, you have who knows how many elements in @_ and you assign them to $bus, @array, $val. The first is assigned to $buf. But how many of the remaining arguments should be assigned to @array? Well, Perl has no way to know. So it assigns all remaining arguments to @array.

Pass a reference to the array instead.

sub busbitFill {
   my ( $bus, $array, $value ) = @_;
   ...
}

busbitFill( $bus, \@array0, $value );   

Don't forget that $array is now a reference to an array rather than an array, and the code for the sub will have to take that into consideration.

ikegami
  • 367,544
  • 15
  • 269
  • 518
  • Perhaps worth noting that when the rest of the sub is implemented, `$array` will have to be dereferenced. Also that the same process may be used for hashes. – Chris Jun 03 '22 at 06:31
  • 1
    The simplest option might be to put the array last `my ($bus, $value, @array) = @_`. – TLP Jun 03 '22 at 11:05
  • @TLP It doesn't look like it's a list of things for the sub to work on, so I would still use a reference here, even if it was last. – ikegami Jun 03 '22 at 13:57