Blog Archive

Thursday, January 27, 2011

Perl hash array Note

1、二维数组
@a=();
@b=("1","2","3");
@c =("4","5","6");
$a[0] = \@b;
$a[1] =\@c;
1>
print  $a[0]->[0],"\n";
print  $a[1]->[0],"\n";
print  $a[0][0],"\n";
print  $a[1][0],"\n";
2>
foreach(@){
 print "${@$_}[2]\n";#will print value of $b[2] and $c[2] 
 print "@$_\n"; #will print value of all
}

Perl格言:(“There’s More Than One Way To Do It”)

2、数组作为子程序参数
eg1.
#!/usr/bin/perl     
    
  @a=(9,2,3,4);   
  @b=("a","b");   
    
  func(\@a,\@b);   
    
  sub   func   {   
  $c=shift;   
  $d=shift;   
  print   $#{@$c},$#{@$d};   
  }
eg2.
#!/usr/bin/perl
@participants=("mark","terry","jason");
@participants2=('33','yts');
my @arr;
$arr[0]=[@participants];
$arr[1]=\@participants2;
print scalar @arr ."\n";
for(my $i=0;$i<scalar @arr;$i++){
        @temp=$arr[$i];
        print scalar @temp," temp's value\n";
        #print "\t [ @{$arr[$i]} ],,\n";
        for(my $j=0;$j<scalar @{$arr[$i]};$j++){
                print $arr[$i][$j],"\n";
        }
}

3、哈希值是数组
my @difs;
my (%records,%record);
@difs1= qw /xx.dif x2.dif y3.dif/;
@difs2= qw /xx1.dif x22.dif/;
$record{"xg3"}=\@difs1; 
$record{"xg5"}=[@difs2];
print "test value:",$record{"xg5"}[1],"\n";
print "-----------------------------2\n";
while(($key,$value)=each %record){
  print "$key:";
  for(my $i=0;$i<scalar @$value;$i++){
     print @$value[$i]," ";
  }
  print "\n";
}
4、数组作为哈希表A的值,哈希表A作为另一哈希表B的值
print "-----------------------------1\n";
#hash as a value in another hash
my @difs;
my (%records,%record1,%record2);
@difs1= qw /x11.txt x22.dif x3.csv/;
@difs2= qw /ya.dif xyz.dif/;
$record1{"xg3"}=\@difs1; 
$record1{"xg5"}=[@difs2];
print "test value:",$record1{"xg5"}[1],"\n";
print "-----------------------------2\n";
while(($key,$value)=each %record1){
  print "$key:";
  for(my $i=0;$i<scalar @$value;$i++){
     print @$value[$i]," ";
  }
  print "\n";
}
print "-----------------------------3\n";
$record2{"xg7"}=\@difs2; 
$record2{"xg8"}=[@difs1];
$records{"RDBMS_MAIN_LINUX_070827"}={%record1};#should not use [ ] here
$records{"RDBMS_MAIN_LINUX_070828"}=\%record2;
while(($key1,$value1)=each %records){
  print "$key1:";
  while(($key2,$value2)=each %$value1){
   print "$key2:";
   for(my $i=0;$i<scalar @$value2;$i++){
      print @$value2[$i]," ";
   }   
  } 
  print "\n";

output:
-----------------------------1
test value:xyz.dif
-----------------------------2
xg5:ya.dif xyz.dif 
xg3:x11.txt x22.dif x3.csv 
-----------------------------3
RDBMS_MAIN_LINUX_070828:xg7:ya.dif xyz.dif xg8:x11.txt x22.dif x3.csv 
RDBMS_MAIN_LINUX_070827:xg5:ya.dif xyz.dif xg3:x11.txt x22.dif x3.csv


Ref:

No comments:

Post a Comment