Reputation: 45
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
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";
Upvotes: 0
Views: 202
Reputation: 126772
The data in the arrays still has the newline at the end of each line read from the file. Use chomp
to fix this.
You should also use strict
and use warnings
at the top of every Perl program.
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";
output
apple, gi joe, iron man, orange, pear, star trek, the blind side
Upvotes: 4