rss· 投稿· 设为首页· 加入收藏· 繁體版
当前位置: 火魔网 » 程序开发 » Perl

perl 一维数组转二维(两种方法比较)

需求是这样的,如下面的数组 a ,要转为 结构为b 的数组。

my @a=qw(a a b b b c c);
my @b=([a,a],[b,b,b],[c,c]);

两种实现方法:

实现方法1 :(使用hash)

#!/usr/bin/perl my @a=qw(a a b b b c c);
my @b=([a,a],[b,b,b],[c,c]);

my %a2h=();
my $i=1;

my @c=();
foreach(@a) $a2h{$_}[$i]=$_;
$i++;    
foreach (values %a2h) push (@c,$_);
}            

foreach(sort @c) foreach($_)    print @{$_},"\n"; }

实现方法2 : 有组合功能

#!/usr/bin/perl

use strict;                                 
use warnings;                               
use Set::CrossProduct;                      

my @a=qw(我的 你的 你的 你的);
my %you_are_not_only;
   foreach(@a)       $you_are_not_only{$_}=$_;   my @onlynumber=(keys %you_are_not_only);
if (scalar(@onlynumber) eq 1)      push (@a,"you_are_not_only");
}

my @bbb=one2two_dim_trans(@a);


sub one2two_dim_trans          my @in_1_dim_arr=@_;
         my $t="999999999999999";
         my @tmp=(['888']);          push (@in_1_dim_arr,'forpush');
         print @in_1_dim_arr,"^^^^^^^^^^^^\n";
         my @holder=([]);
         for my $i(@in_1_dim_arr)                 if ($t ne $i)                       shift @tmp;
                      push(@holder,[@tmp]);
                      #print "___tmp___","@tmp","__####\n";
                      @tmp=(['']);                 push(@tmp,$i);
                $t=$i;
              #print "sss=======",@holder,"\n";          shift(@holder);
         shift(@holder);
         print "$holder[0]","-----------------\n";          my $iterator = Set::CrossProduct->new( \@holder );
         my @tuples = $iterator->combinations;
         my @out=map{"@$_\ "} @tuples;
      #   print @out,"\n\n";
         return @out;                 
for my $elmt(@bbb)           my @com=split(' ',$elmt);
          my %cell_ha;
          print @com,"\n";
          for my $incom(@com)            $cell_ha{$incom}=$incom;
           print "----",$cell_ha{$incom},"\n";           #print "-----group hs4--------\n"       
      

顶一下
(0)
踩一下
(0)