0

I tried writing a subroutine that iterates through a list of strings and prints each string, but it doesn't work:

use HTTP::Date;

my @date_strings_array = ("Jun 1, 2026", "Aug 26, 2018 GMT-05:00", "Aug 26, 2018");
print_datetimes(@date_strings_array);

sub print_datetimes {
    my @date_string_array = shift;

    foreach $date_string (@date_string_array) {
       print("The current iteration is $date_string.");  
    }
 }

It only prints the first iteration:

$ perl /example/test.pl
The current iteration is Jun 1, 2026.

Why does this only print the first item in the array?

2 Answers 2

3

shift only retrieves one element. You can assign the whole argument array, though:

my @date_string_array = @_;
for my $date_string (@date_string_array) {
    ...
Sign up to request clarification or add additional context in comments.

5 Comments

Wow - that's quite irritating. This works - thanks! :)
Irritating? I almost always use my ($self, $whatever) = @_ instead of shifting @_.
I mean that your answer makes sense and is elegant. But as a language feature, the syntactic differences between shift and @_ are very dramatic. It's very non-intuitive to me.
It's not "differences between shift and @_" as both versions deal with @_ (shift() acts on @_ if given no other argument). The difference is between shift() (which removes a single element from the start of an array) and list assignment (which copies all values from the list on the right hand side ot the operator into variables on the left hand side of the operator).
You could, of course, do this without your @date_string_array variable. foreach my $date_string (@_) { print ... } or even just print "... $_" for @_
1

You need to pass the refenrece to array.

my @date_strings_array = ("Jun 1, 2026", "Aug 26, 2018 GMT-05:00", "Aug 26, 2018");
print_datetimes(\@date_strings_array);

sub print_datetimes {
    my $date_string_array = shift;

    foreach my $date_string (@$date_string_array) {
       print "The current iteration is $date_string.\n";  
    }
 }

1 Comment

You might want to consider switching to passing array references and to @_ as choroba has suggested. Next time you may want to pass two arrays, and print them separately.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.