0

If I do:

foreach my $comp (@compList){
  print $comp .= "\n";
  @component_dirs = DoStuff($comp); 
} 

My output is simply:

String1
String2
String3
...

However, once I get into the method DoStuff(), I do:

sub DoStuff{
  my $strComponentName = @_;
  print "\t$strComponentName\n";
}

With this, my output becomes

String1
        1
String2
        1
String3
        1
...

Why?

MrDuk
  • 16,578
  • 18
  • 74
  • 133

2 Answers2

3

You are assigning the array @_ to a scalar $strComponentName.

In scalar context, the result of an array is the number of elements in the array.

In your case it's 1, because you call DoStuff with one parameter.

To actually get the parameter, you would have to write

my ($strComponentName) = @_;

This will assign an array to an array, where the first variable in the left array will contain the first element of the right array.

Karsten S.
  • 2,349
  • 16
  • 32
3

To capture the elements of the array @_, your left hand side must be a list:

sub DoStuff{
  my ($strComponentName) = @_;

Otherwise, the array is evaluated in a scalar context and will just return the element count.

The other alternative is to specify the specific element you want in your assignment.

  my $strComponentName = $_[0];

Or shift the first element off the array

  my $strComponentName = shift;
Miller
  • 34,962
  • 4
  • 39
  • 60