Perl `join` 生成多行字符串 [英] Perl `join` produces multi-line string
问题描述
我有这个程序来对两个数组进行排序
I have this program to sort two arrays
#!/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;
当我运行它时,我得到了这样的东西
When I run it I get something like this
apple
gi joe
iron man
orange
pear
star trek
the blind side
我怎样才能把它改成这个样子?
How can I change it to look like this?
apple, gi joe, iron man, orange, pear, star trek, the blind side
我知道它与join
有关,但是如果我将程序更改为此,它仍然会在多行上打印输出
I know it has something got to do with join
, but if I change my program to this it still prints the output on multiple lines
$value = join(', ', @array3);
print "$value\n";
推荐答案
数组中的数据在从文件中读取的每行末尾仍然有换行符.使用 chomp
来解决这个问题.
The data in the arrays still has the newline at the end of each line read from the file. Use chomp
to fix this.
您还应该在每个 Perl 程序的顶部use strict
和use warnings
.
You should also use strict
and use warnings
at the top of every Perl program.
最好的做法是使用词法文件句柄和三参数形式的open
,并且您的 die
字符串应包含内置的 $!
变量说为什么打开
失败.
It is best practice to use lexical file handles with the three-parameter form of open
, and your die
string should include the built-in $!
variable to say why the open
failed.
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
这篇关于Perl `join` 生成多行字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!