简体   繁体   English

从perl中的循环中删除多余的选项卡

[英]removing excess tab from loop in perl

a basic question involving loops. 一个涉及循环的基本问题。 If I'm doing a basic loop where I want to generate a tab delimited table from a hash of hashes (format: $hash_of_table_data{$headers}{$entry} = 1) with example code: 如果我正在执行一个基本循环,那么我想使用示例代码从哈希散列(格式:$ hash_of_table_data {$ headers} {$ entry} = 1)生成一个制表符分隔的表:

foreach my $rowheader (keys %hash_of_table_data) {
  print "$rowheader\t";
  foreach my $entry (keys %{ $hash_of_table_data{$rowheader}}) {
    print "$entry\t";
  }
  print "\n";
}

So, by doing loops like this, at the end of print my last element of each row, it will have an extra tab. 因此,通过执行这样的循环,在打印每一行的最后一个元素的末尾,它将有一个额外的选项卡。 Is there a simple way to generate a similar list but that wouldn't add the extra tab at the very end? 是否有一种简单的方法来生成类似的列表,但不会在最后添加额外的标签? Or some simple chomp like function that will remove the last tab added prior to doing the new line? 还是一些简单的类似chomp的函数,它将删除在执行新行之前添加的最后一个标签? (I want it to add tabs between every element, except the final element). (我希望它在除最后一个元素之外的每个元素之间添加制表符)。

As people have commented, join seems to be a nice solution for this problem. 正如人们所说, join似乎是解决此问题的一个不错的解决方案。 You can do this in a single line: 您可以单行执行此操作:

print join("\t", $_, keys %{$hash{$_}}) . "\n" foreach keys %hash;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM