在perl中创建具有多个coloumn的多维数组

时间:2015-06-10 14:37:51

标签: perl

ID  Cat    
1   Car          
2   Education     
3   Mathematics   
4   Physics       
5   Astrophysics

基于此列表,我想以下列方式生成和访问数组:

Array
(
    [0] => Array
        (
            [id] => 1
            [cat] => car
        )

    [1] => Array
        (
            [id] => 2
            [cat] => Education
        )

      [2] => Array
        (
            [id] => 3
            [cat] => Mathematics
        )   


)

依此类推,直到阵列结束。

1 个答案:

答案 0 :(得分:5)

执行此操作的一种简单方法是逐行读取文件,将每行拆分为id和category部分,并使用这些部分创建哈希引用数组

use strict;
use warnings; 

use Data::Dumper;

my @categories;
while ( my $row = <DATA> ) {
   my ($id, $cat) = $row =~ m/(\d+)\s+(\w+)/;

   push @categories, { id => $id, cat => $cat };
}

print Dumper \@categories; 

__DATA__
1 Car
2 Education
3 Mathematics
4 Physics
5 Astrophysics 

输出:

$VAR1 = [
          {
            'cat' => 'Car',
            'id' => '1'
          },
          {
            'cat' => 'Education',
            'id' => '2'
          },
          {
            'cat' => 'Mathematics',
            'id' => '3'
          },
          {
            'cat' => 'Physics',
            'id' => '4'
          },
          {
            'cat' => 'Astrophysics',
            'id' => '5'
          }
        ];

如果您的文件比此复杂(例如有引用),您应该使用Text::CSV_XS