首页 > 解决方案 > 如何在 PERL 中打印数组引用的值?

问题描述

我在 Perl 中有一个带方括号的定义天数数组。我想访问数组的每个元素。下面代码中的一个类似示例(这只是一段代码):-

@days = [a,2,3];
foreach(@days){print "$_\n";}
print "\n\n @days";

输出为 ARRAY(0x2032950)

数组(0x2032950)

我需要访问数组 elementS 但我无法更改 @days 声明。以下代码也无法正常工作:-

 @days = [a,2,3];
    use feature qw<say>;    
    foreach(@days){print "$_\n";}
    print "\n\n @days\n";
    print "@$days\n";
    say $_ for $days->@*;

在此处输入图像描述

标签: perl

解决方案


Attn: OP - 数组声明不正确。

如果您无法更改数组声明(不清楚是什么原因),请使用以下代码打印它们

use strict;
use warnings;
use feature 'say';

my @days = ['a',2,3];

say for @{$days[0]};

say "Number of elements: " . scalar @{$days[0]};

正确的代码应该是

use strict;
use warnings;
use feature 'say';

my @days = ('a',2,3);

say for @days;

say "Number of elements: " . scalar @days;

以下代码演示了数组是如何创建的,使用这些信息很容易弄清楚如何访问数组元素的存储值

use strict;
use warnings;
use feature 'say';

use Data::Dumper;

my @days = ['a',2,3];

say Dumper(\@days);

输出

$VAR1 = [
          [
            'a',
            2,
            3
          ]
        ];

推荐阅读