3

我有一个文件

#File content
   word1 -> word2
word3 -> word4

我需要把它放在2个不同的数组中

@array1 = word1, word3
@array2 = word2, word4

我的代码如下

my @mappings = `cat $file_name`; 
foreach my $map (@mappings) { 
    $map =~ s/^\s+|\s+$//g; #Remove leading and trailing spaces 
    next if ($map =~ /^#/); 
    my @Mainarray = split ('->',$map); 
    my @array1 = push(@array1,@Mainarray[0]); **#Error line**
    my @array2 = push(@array2,@Mainarray[1]); **#Error line**
    print("Array1: @array1\nArray2:@array2\n"); 
}

我收到此错误:

Global symbol "@array1" requires explicit package name.
Global symbol "@array2" requires explicit package name.

有人可以帮我解决这个问题。

4

1 回答 1

3

您拥有它的方式是每次通过 foreach 循环重新定义@array1& @array2,并尝试将它们设置为等于包含未定义值(本身)的值。尝试这个:

my @mappings = `cat $file_name`;
my @array1;
my @array2;
foreach my $map (@mappings) { 
  $map =~ s/^\s+|\s+$//g; #Remove leading and trailing spaces 
  next if ($map =~ /^#/); 
  my @Mainarray = split (/->/,$map); 
  push(@array1, $Mainarray[0]); 
  push(@array2, $Mainarray[1]);
  print("Array1: @array1\nArray2:@array2\n"); 
}
于 2013-09-25T18:16:49.923 回答