【问题标题】:Problems iterating over array遍历数组的问题
【发布时间】:2018-06-19 23:33:13
【问题描述】:

我尝试编写一个子程序来遍历字符串列表并打印每个字符串,但它不起作用:

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.");  
    }
 }

它只打印第一次迭代:

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

为什么只打印数组中的第一项?

【问题讨论】:

    标签: perl


    【解决方案1】:

    shift 只检索一个元素。不过,您可以分配整个参数数组:

    my @date_string_array = @_;
    for my $date_string (@date_string_array) {
        ...
    

    【讨论】:

    • 哇——这很烦人。这有效 - 谢谢! :)
    • 烦人?我几乎总是使用my ($self, $whatever) = @_ 而不是转移@_。
    • 我的意思是你的回答很有意义而且很优雅。但作为语言特性,shift@_ 之间的句法差异非常显着。这对我来说非常不直观。
    • 这不是“shift@_ 之间的差异”,因为两个版本都处理 @_(如果没有其他参数,shift() 作用于 @_)。区别在于shift()(从数组的开头删除单个元素)和列表赋值(将运算符右侧列表中的所有值复制到运算符左侧的变量中) .
    • 当然,您可以在没有 @date_string_array 变量的情况下执行此操作。 foreach my $date_string (@_) { print ... } 甚至只是 print "... $_" for @_
    【解决方案2】:

    您需要将引用传递给数组。

    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";  
        }
     }
    

    【讨论】:

    • 您可能需要考虑切换到传递数组引用和 @_,正如 choroba 所建议的那样。下次你可能想要传递两个数组,并分别打印它们。
    猜你喜欢
    • 2018-02-13
    • 2019-08-29
    • 1970-01-01
    • 1970-01-01
    • 2012-11-21
    • 2019-04-03
    • 2016-11-05
    • 2019-05-22
    相关资源
    最近更新 更多