简单的Perl for-loop错误

时间:2016-05-27 02:38:37

标签: perl

for ($i=1; $i<=3; $i++) {
    if ( @user$i[3] >= 4.0 ) {
        print "first";
    } elsif ( @user$i[3] < 4.0 and @user$i[3] >= 2.5 ) {
        print "second";
    } else {
        print "third";
    }
}

不起作用

我想在代码

下面使用相同的功能

你能给我一些帮助吗

if ( @user1[3] >= 4.0 ) {
     print "first";
} elsif ( @user1[3] < 4.0 and @user1[3] >= 2.5 ) {
     print "second";
} else {
     print "third";
}

if ( @user2[3] >= 4.0 ) {
    print "first";
} elsif ( @user2[3] < 4.0 and @user2[3] >= 2.5 ) {
    print "second";
} else {
    print "third";
}

if ( @user3[3] >= 4.0 ) {
    print "first";
} elsif ( @user3[3] < 4.0 and @user3[3] >= 2.5 ) {
    print "second";
} else {
    print "third";
}

1 个答案:

答案 0 :(得分:1)

使用引用迭代不同的数组。

perldoc perlref - perl参考

perldoc perldsc - perl数据结构cookbook

#/usr/bin/env perl

use strict;
use warnings;

my @user1 = ( 1, 2, 3, 4 );
my @user2 = ( 4, 3, 1, 2 );
my @user3 = ( 2, 1, 4, 3 );

my $data = [ \@user1, \@user2, \@user3 ];
my $field = 3; # Fourth field, perl is 0-based                                           

for my $users ( @$data ) {
    # $users->[...] instead of $users[...] because $users is an array reference             
    if ( $users->[$field] >= 4.0 ) {
        print "first";
    } elsif ( $users->[$field] < 4.0 and $users->[$field] >= 2.5 ) {
        print "second";
    } else {
        print "third";
    }
    print "\n";
}

输出

first
third
second