通过赋值给变量来打印数组元素

时间:2014-06-19 09:40:25

标签: perl

我无法按预期打印数组元素值。 @array = (1,2,3,4,5,6,7,8);

我想将第一个值分配给变量a,将第二个值分配给变量b

for (my $index = 0; $index <= $# array; $index++) {
    my $a = @array[$index];
    my $b = @array[$index + 1];
    DEBUG("DEBUG:: $a and $b");
}

我想输出

    a=1 and b=2
    a=3 and b=4
    a=5 and b=6

6 个答案:

答案 0 :(得分:1)

您的问题的根本原因是您应该使用'$ index = 2'而不是'$ index ++'来增加$ index。

答案 1 :(得分:0)

#!/usr/bin/perl
use strict;
use warnings;

my @array = (1,2,3,4,5,6,7,8);

my %hash = @array;

while (my ($key,$value) = each %hash) {
    print "Key is $key, Value is $value\n";
}

Demo

另一种方式

#!/usr/local/bin/perl
use strict;
use warnings;
my @array = (1,2,3,4,5,6,7,8);
for (my $count=0; $count<@array; $count+=2){
    print "A is $array[$count], B is $array[$count+1]\n";
}

Demo

你的方式

#!/usr/local/bin/perl
use strict;
use warnings;
my @array = (1,2,3,4,5,6,7,8);
for ( my $index=0;$index<=$#array;$index+=2)   {
    my $a1 = @array[$index];
    my $b1 = @array[$index+1]; 
    print "A is $a1, B is $b1\n";
}

Demo

答案 2 :(得分:0)

当我理解你的问题时,你想要一个循环,递增2:

use strict;
use warnings;
use feature 'say';
my @array = (1, 2, 3,4,5,6,7,8);
my (@array_a, @array_b);
for (my $count=0; $count < $#array; $count+=2) {
  say "a is $array[$count], b is $array[$count+1]";
}

输出:

a is 1, b is 2
a is 3, b is 4
a is 5, b is 6
a is 7, b is 8

答案 3 :(得分:0)

您可以使用模数运算符:

#!/usr/bin/perl
use warnings;
use strict;

my @array = (1 .. 8);

foreach (@array){
    $_ % 2 == 0 ? print "b = $_\n" : print "a = $_\t";
}

-

a = 1   b = 2
a = 3   b = 4
a = 5   b = 6
a = 7   b = 8

答案 4 :(得分:0)

正如其他人所说,简单的解决方法是将循环增量器更改为+= 2。另一种方法是使用splice

my @array = (1,2,3,4,5,6,7,8);

while (my ($x, $y) = splice @array, 0, 2) {
    DEBUG("DEBUG:: $x and $y");
}

这会删除@array中的项目,因此您可能需要先制作副本。

答案 5 :(得分:0)

尚未提及的一种非常简单的方法:

while (@array) {
    my $x = shift(@array);
    my $y = shift(@array);
    DEBUG("DEBUG:: $x and $y");
}

但是,它有清空@array的副作用。