簡體   English   中英

從perl文件中僅打印一行中由制表符分隔的十個單詞

[英]to print only ten words separated by tab in a line from a file in perl

#! /bin/usr/perl
print "Enter your database name: \n";
chomp($db=<STDIN>);
open(R1,"$db")||die("error");
while ($line1=(<R1>)) {
    $l1=$line1;
    @arr1= split("  ",$l1);
    for $i=(0..9)
    {
        print  "@arr1[$i] \t";
        print join (@arr1), "\n";
    }
}
close(R1);
exit;

我只想有十個單詞,或者(數字也算作一個單詞),但是我得到的只是第一個單詞,剩下的十個單詞是空白。

所需的輸出:

1我叫abcde fg

你的名字叫米切爾(Micheal),你在5年級學習

代碼的最初問題是語法錯誤。 第二個問題是您沒有告訴Perl幫助您編寫更好的代碼。 幾乎所有的Perl代碼都應use strict; use warnings;代碼use strict; use warnings; use strict; use warnings; ,因此您的代碼應該開始

#! /bin/usr/perl
use strict;
use warnings;

use strict; 這將意味着您必須聲明所有使用的變量,但這是一件好事。 這兩行還將指出語法錯誤。

唯一不應該use strict; Perl程序use strict; use warnings; 是他們的作者確切知道為什么被省略並可以向其他人解釋原因的地方。

perl -wnlaF'\t' -E 'say join "\t", @F[0 .. (9 <= $#F ? 9 : $#F)]' input.txt > output.txt

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM