Perl:Perl6 :: Form格式 [英] Perl: Perl6::Form format

查看:46
本文介绍了Perl:Perl6 :: Form格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的文件

SR   Name               Rollno   Class

1    Sanjay              01       B
2    Rahul_Kumar_Khanna  09       A

现在我需要添加"|"彼此之间.所以应该看起来像

Now I need to add "|" between each. So it should look like

SR | Name              |Rollno | Class|

1  | Sanjay            |01     | B    |
2  | Rahul_Kumar_Khanna|09     | A    |

我正在使用Perl6 :: form

I am using Perl6::form

my $text;
        
foreach my $line (@arr) {
    my ($SR, $Name, $Rollno, $Class) = split (" ", $line);
    my $len = length $Name;
    $text = form 
        '| {||||||||} | {||||||||} | {||||||||} | {||||||||}|', 
            $SR,         $Name,       $Rollno,     $Class;
    print $text;
}

到现在为止,我已经完成了,但是名字不正确.我添加了额外的"|"以此为名.有什么办法可以添加"|"?通过计算长度(如下).我尝试了但出错了.

Here till now I have done but the name is not comming out properly. I have add extra "|" in name for that. Is there any way we can add "|" by calculating length like(below). I tried but getting error.

'| {||||||||} | {||||||||}x$len | {||||||||} | {||||||||}|',

推荐答案

问题1

'| {||||||||} | {||||||||}x$len | {||||||||} | {||||||||}|'

产生

| {||||||||} | {||||||||}x20 | {||||||||} | {||||||||}|

但您正在尝试获取

| {||||||||} | {||||||||||||||||||||} | {||||||||} | {||||||||}|

为此,您想要

'| {||||||||} | {'.( "|" x $len ).'} | {||||||||} | {||||||||}|'


问题2

$ len 是当前行的名称字段的长度.每行都不同.这是错误的,因为您希望输出的每一行的宽度都相同. $ len 必须是最长名称字段的长度.

$len is the length of the name field of the current row. It's different for every row. This is wrong, cause you want the output to be the same width for every row. $len needs to be the length of the longest name field.

在开始循环之前,您需要找到 $ len 的正确值.

You will need to find the correct value for $len before even starting the loop.

# Read in the data as an array of rows.
# Each row is an array of values. 
my @rows = map { [ split ] } <>;

# Find the maximum width of each column. 
my @col_lens = (0) x @{rows[0]};
for my $row (@rows) {
   # Skip the blank line after the header. 
   next if !@$row;

   for my $col_idx (0..$#$row) {
      my $col_len = $row->[$col_idx];
      if ($col_lens->[$col_idx] < $col_len) {
         $col_lens->[$col_idx] = $col_len;
      }
   }
}

my $form =
   join "",
      "| ",
      "{".( "|"x($col_lens[0]-2) )."}",
      " | ",
      "{".( "|"x($col_lens[1]-2) )."}",
      " | ",
      "{".( "|"x($col_lens[2]-2) )."}",
      " | ",
      "{".( "|"x($col_lens[3]-2) )."}",
      " |";

for my $row (@rows) {
   if (@$row) {
      print form($form, @$row);
   } else {
      print "\n";
   }
}

这篇关于Perl:Perl6 :: Form格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆