Perl语言学习(5)- 二维数组

二维数组

  • 程序功能描述
  • Perl源代码
  • 运行结果

程序功能描述

使用二维数组,存储从文本中提取到的列表形式的数据,转换为规范的格式。
对于二维数组,可以直接使用以下方式:

$data_matrix[$row][$col] = " ";# 对数组赋值即可
$var = $data_matrix[$row][$col];# 读取数组内容

程序中也调用了shell的find命令查找当前目录下以.txt结尾的文件。

Perl源代码

#!/user/bin/perl -w
use strict;

my @files;
my $file_type = "*.txt";
my $file_name;
my $outfile_name = "out.txt";
my @data_matrix;
my $row_num = 0;
my $col_num = 0;
my $str = "";

@files = `find ./ -name $file_type`;
$file_name = $files[0];
chomp $file_name;


open(LOG,"<",$file_name) or die "Can not open $file_name for reading!\n";

while (defined(my $line = ))
{
     
	chomp $line;
	next if ($line =~ /\A\s*\z/);
	$line =~ s/\A\s*|\s*\z//g;
	
	# first line
	if($line =~ /\Aname\s/)
	{
     
        while($line =~ /\A([a-zA-Z]+)/)
        {
     
            $data_matrix[$row_num][$col_num] = $1;
            $col_num++;
            $line =~ s/\A[a-zA-Z]+\s*//g;# delete first element each time
        }
        $row_num++;
	}
    # other line
	elsif($line =~ /\A\S+\s/)
	{
     
        my $col_cnt = 0;
        while($line =~ /\A(\S+)/)
        {
     
            $data_matrix[$row_num][$col_cnt] = $1;
            $col_cnt++;
            $line =~ s/\A\S+\s*//g;# delete first element each time
        }
        $row_num++;
	}
}

close (LOG);

foreach my $row (0..($row_num-1))
{
     
    foreach my $col (0..($col_num-1))
    {
     
        $str .= $data_matrix[$row][$col] . " "x(20 - (length $data_matrix[$row][$col]));
    }
    $str .= "\n";
    $str .= "-"x(20 * $col_num) . "\n" if ($row == 0);
}

open(OUT,">",$outfile_name) or die "Can not open $outfile_name for writting!\n";
print OUT $str;
close (OUT);
print "\nThe file $outfile_name has been generated!\n\n";


运行结果

待处理的文件CoverageReport.txt:(格式不对齐)

name      CodeAverage     FunctionalCovered  
----------------------------------------------
tb_aaa     98.68%           83.33%(15/18) 
tb_bbb     85.87%           57.65%(49/85)
tb_ccc    98.56%           95.00%(19/20)
tb_ddd     99.92%           78.36%(315/402)
tb_eee    96.73%            77.14%(54/70)
tb_fff     98.50%          100.00%(68/68)
tb_ggg     85.55%          99.35%(152/153)

Perl语言学习(5)- 二维数组_第1张图片

处理结果out.txt:(格式对齐)

name                CodeAverage         FunctionalCovered   
------------------------------------------------------------
tb_aaa              98.68%              83.33%(15/18)       
tb_bbb              85.87%              57.65%(49/85)       
tb_ccc              98.56%              95.00%(19/20)       
tb_ddd              99.92%              78.36%(315/402)     
tb_eee              96.73%              77.14%(54/70)       
tb_fff              98.50%              100.00%(68/68)      
tb_ggg              85.55%              99.35%(152/153)     

Perl语言学习(5)- 二维数组_第2张图片

你可能感兴趣的:(Perl脚本,perl)