如何在perl中使用两个数组创建表

时间:2013-10-23 17:24:09

标签: arrays perl cgi

需要帮助才能使用perl cgi中的两个数组或文件创建表。

我需要创建一个表来打印来自不同路径的目录列表然后将其放入表中,表示第一列上的标题表示path1和第2列path2,依此类推,每列用href列出该路径中的目录链接......我所拥有的。

 opendir(D, "../abc/status") or die"$!"; 
 my @path1_dir = sort readdir D; closedir D;

 opendir(D, "../def/status") or die "$!"; 
 my @path2_dir = sort readdir D; closedir D; .... ...

 print "\n"; print "$path1_dir\n"; print "$path2_dir\n";

 #print list of directories to column-1 with title Path1
 foreach my $path (@path1_dir) { 
   print "\t\n"; 
   next if ($path =~ /^./); 
   next if ($path =~ /^\s*$/); 
  print "$path\n"; 
 }

 #this should go to the column two with Path2 title but it does not
 foreach my $path (@path2_dir) { 
   print "\t\n"; `enter code here`
   next if ($path =~ /^./); 
   next if ($path =~ /^\s*$/); 
   print "$path\n"; 
   }

如果可以,有人可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

我认为你想根据你的描述想要这样的东西 - 即在两列中打印

    $dir1 = "../abc/status";
    $dir2 = "../def/status";
    opendir(D, $dir1) or die"$!";
    my @path1_dir = sort grep { !/(^\.|^\s*$)/ } readdir D; closedir D;

    opendir(D, $dir2) or die "$!"; 
    my @path2_dir = sort grep { !/(^\.|^\s*$)/ } readdir D; closedir D;

    print "$dir1\t$dir2\n";

    # figure out which one has more files
    $limit = $#path1_dir < $#path2_dir ? $#path2_dir : $#path1_dir;

    # print in 2 columns
    for ($i = 0; $i<=$limit; $i++) {
       printf "%s\t%s\n",
            ($i<=$#path1_dir ? $path1_dir[$i] : ""),
            ($i <= $#path2_dir ? $path2_dir[$i] : ""),"\n";
    }

答案 1 :(得分:0)

虽然目前尚不清楚你想要什么,但我猜你想要为FTP或其他东西设置一个ls样式输出(只有目录)。变量命名可能不明确,但基本上它正在做的是一次从每个目录打印一个目录。

#!/usr/bin/perl

use strict;
use warnings;

my %dirs;

my @dirs_to_look = qw(../abc ../def);
my $max_num_of_dirs;

foreach my $dir (@dirs_to_look) {
    # Directories that were found in $dir
    my @dirs_in_dir = grep { -d } glob "$dir/*";
    $max_num_of_dirs = scalar @dirs_in_dir
        if not defined $max_num_of_dirs or $max_num_of_dirs < scalar @dirs_in_dir;
    $dirs{$dir} = \@dirs_in_dir;
}

my @keys = sort {$a cmp $b} keys %dirs;
# Print the column titles
foreach my $key (@keys) {
    printf "%15s", $key;
}
print "\n";

for (my $i = 0; $i < $max_num_of_dirs; $i++) {
    foreach my $key (@keys) {
        my $dir = shift @{ $dirs{$key} };
        printf "%15s", $dir // "";
    }
    print "\n";
}