且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

perl-将array的值放在一个数组中

更新时间:2023-02-10 19:52:06

您的代码看起来很奇怪。

Your code looks rather strange.

#!/usr/bin/perl use DBI; use Data::Dumper; use DBD::mysql; use POSIX;

这看起来好像都应该不在同一行。

That doesn't look like it should all be on the same line.

#use strict; use warnings;

评论这些是一个非常糟糕的主意!

Commenting those out is a very bad idea!

foreach my $line(@lines) {

    @temp_arr=split('\s',$line);

    push(@temp_arr);

我不确定您在这里做什么吗? push()需要(至少)两个参数-一个数组(您拥有)和一些要添加到该数组中的项目(您已省略)。没有第二个参数, push()不会执行任何操作。

I'm not sure what you think you're doing here? push() takes (at least) two arguments - an array (which you have) and some items to add to the array (which you've omitted). Without a second argument, push() does nothing.

    #print "$temp_arr[0] $temp_arr[1] $temp_arr[2] $temp_arr[3] $temp_arr[4] $temp_arr[5] $temp_arr[6] $temp_arr[7] $temp_arr[8] $temp_arr[9] $temp_arr[10] $temp_arr[11] $temp_arr[12]\n";

这似乎是写 print @ temp_arr\ n :-)

    @splited_line = "$temp_arr[0] $temp_arr[1] $temp_arr[2] $temp_arr[3] $temp_arr[4] $temp_arr[5] $temp_arr[6] $temp_arr[7] $temp_arr[8] $temp_arr[9] $temp_arr[10] $temp_arr[11] $temp_arr[12]\n";

好的,这就是您要出错的地方。您将 @temp_arr 的所有元素放入字符串中,然后将该(单个)字符串分配给 @splited_line 。这使 @splited_line 保留一个元素-包含您的字符串。您可能想要的只是 @splited_line = @temp_arr

Ok, so this is where you're going wrong. You are putting all of the elements of @temp_arr into a string and then assigning that (single) string to @splited_line. This leaves @splited_line with one element - containing your string. What you probably want is just @splited_line = @temp_arr.

    push(@splited_line);

另一个毫无意义的 push()。为什么要将它们添加到代码中?

Another pointless push(). Why are you adding those to your code?

    print $splited_line[2];

由于 @splited_line 仅包含一个元素, $ splited_line [2] 将包含 undef

As @splited_line only contains one element, $splited_line[2] is going to contain undef.

}

我想您想要这样的东西:

I think you want something like this:

#!/usr/bin/perl

# strict and warnings before all other code
use strict;
use warnings;

use DBI;
use Data::Dumper;
# You don't usually need to load DBD modules
use DBD::mysql;
use POSIX;

# 3-arg open() and lexical filehandle
# Check return from open().
open(my fh, '<', 'titi.log') or die "Cannot open file: $!\n";
print "file loaded \n";

# Do you really need to read the whole file in here?
my @lines = <$fh>; #tout les valeurs du fichier se trouve dans le tableau lines 
close($fh);

# No need to quote this values.
print $lines[0];
print $lines[83000];

foreach (@lines) {
    # By default, split() splits $_ on whitespace
    my @temp_arr = split;

    print "@temp_arr\n";

    my @splited_line = @temp_arr;

    print $splited_line[2]; 
}