将元素连接到数组中并与空格分开

时间:2017-05-22 08:55:46

标签: perl join

我希望在一个数组中加入第一个到第16个字和第17个到第31个等,其中空格为一行,但不知道为什么代码不起作用。希望在这里得到帮助。谢谢

my @file = <FILE>;
for ( $i=0; $i<=$#file; $i+=16 ){
    my $string = join ( " ", @file[$i..$i+15] );
    print FILE1 "$string\n";
}

以下是我档案的一部分。

1
2
3
...

我要打印的是

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
17 18 19 20 21....

4 个答案:

答案 0 :(得分:5)

我不会像你那样做。

相反,我会:

open ( my $input, '<', "your_file_name" ) or die $!;
chomp ( my @file = <$input> ); 
print join (" ",splice (@file, 0, 15)),"\n" while @file;

注意 - 我使用了一个打开3参数的词法文件句柄,因为这样的风格更好。

splice每次迭代都会从@file中删除前16个元素,并一直持续到@file为空。

答案 1 :(得分:2)

你的专栏附有换行符。使用chomp删除它们。然后循环遍历数组,删除16个项目并打印它们。

my @file = <FILE>;
chomp @file;

while (@file) {
    my @temp;
INNER: for ( 0 .. 15 ) {
        push @temp, shift @file || last INNER; # not or
    }
    print join( q{ }, @temp ), "\n";
}

这是the splice solution Sobrique suggested in the comments的长期实施。它做同样的事情,只是更冗长。

这是编辑前的旧答案:

如果你只想要前16,那就更有效了。

my $string = join q{ }, map { <FILE>; chomp; $_ } 1 .. 16;

这将分别读取16行和chomp,然后join s。

您可能还想使用词法文件句柄$fh而不是GLOB FILE

open my $fh, '<', $path_to_file or die $!;

答案 2 :(得分:2)

假设您要从文件中读取它,请不要将整个文件存储到数组中。而是逐行循环。并使用<div class="row" *ngFor="let item of items"> <div (click)="item.opened = !item.opened" class="div-one"> </div> <div *ngIf="item.opened" class="div-open"> </div> </div> 特殊变量检查行号。

$.

或者这也可行

use warnings;
use strict;
open my $fh,"<","input.txt";
my $line;
while (<$fh>)
{
    chomp;

    $line.= $_." ";

    print "$line\n" and $line="" if($. % 16 == 0);

    END{ print "$line\n";};
}

答案 3 :(得分:1)

假设您打开了FILE和FILE1描述符,请尝试:

$.%16?s!\s+! !:1 and print FILE1 $_ while <FILE>;
相关问题