I have an array populated with cities. I want to pass the array by reference to a sub routine and print each city to output. However, I have the following problems:
I can access each element before my while loop in the subroutine. But I cannot access the elements within my while loop. I get the error message:
... Use of uninitialized value in print at line 44, line 997 (#1) Use of uninitialized value in print at line 44, line 998 (#1) ...
The following is some code. I have commented what prints and what doesn't (I tried to cut out code that is not needed for my explanation...):
@cities;
# Assume cities is loaded successfully
&loadCities(getFileHandle('cities.txt'), $NUM_CITIES, \@cities);
&printElements(getFileHandle('names.txt'), \@cities);
sub printElements{
my $counter = 0;
my $arraySize = scalar $_[1];
# Prints fine!!!
print @{$_[1][($counter)%$arraySize];
while ((my $line = $_[0]->getline()) && $counter < 1000){
# Doesn't print. Generates the above error
print @{$_[1][($counter)%$arraySize];
$counter += 1;
}
}
- The Perl syntax has me super confused. I do not understand what is going on with @{$_[1]}[0]. I am trying to work it out.
- $_[1], treat the value at this location as scalar value (memory address of the array)
- @{...}, interpret what is stored at this memory address as an array
- @{...} [x], access the element at index x
Am I on the right track?