Perl`comth`生成多行字符串

时间:2014-05-18 14:43:21

标签: perl

我有这个程序来排序两个数组

#!/usr/bin/perl -w

$movies = 'movies.txt';
open (FHD, $movies) || die " could not open $movies\n";
@movies = <FHD>;

$fruits = 'fruits.txt';
open (FHD, $fruits) || die " could not open $fruits\n";
@fruits = <FHD>;

@array3 = (@movies , @fruits);
@array3 = sort @array3;

print @array3;

当我运行它时,我得到类似的东西

apple
gi joe
iron man
orange
pear
star trek
the blind side

如何将其更改为这样?

apple, gi joe, iron man, orange, pear, star trek, the blind side

我知道它与join有关,但如果我将程序更改为此,它仍然会在多行上打印输出

$value = join(', ', @array3); 
print "$value\n";

1 个答案:

答案 0 :(得分:3)

数组中的数据在从文件读取的每一行的末尾仍然有换行符。使用chomp来解决此问题。

您还应该在每个 Perl程序的顶部use strictuse warnings

最佳做法是使用词法文件句柄三参数形式open,并且您的die字符串应包含内置$!变量,以说为什么 open失败。

use strict;
use warnings;

my $movies = 'movies.txt';
open my $fh, '<', $movies or die "Could not open '$movies': $!\n";
my @movies = <$fh>;
chomp @movies;


my $fruits = 'fruits.txt';
open $fh, '<', $fruits or die "Could not open '$fruits': $!\n";
my @fruits = <$fh>;
chomp @fruits;

my @array3 = sort @movies, @fruits;

print join(', ', @array3), "\n";

<强>输出

apple, gi joe, iron man, orange, pear, star trek, the blind side