Mateusz
Mateusz

Reputation: 331

Read file to one string and separate it in perl

So I have file which looks like:

Name, Surname, Number
Name2, Surname2, Number2
Name3, Surname3, Number3

I want to read it all to one string in Perl, and I want it to look like:

"Name, Surname, Number, Name2, Surname2, Number2, Name3, Surname3, Number3"

But I really don't have idea how to do it :/ I'm new in Perl. I know only, that to open file I need to do:

open($list, "<", $file)

Upvotes: 2

Views: 143

Answers (3)

Resident Reporter
Resident Reporter

Reputation: 7

The other answers will work. Since you're new to Perl like me, a different but perhaps more beginner-friendly (straightforward, IMO) way of doing it would be:

use strict;

sub main(){

my $output; 
    open( 'sourcefile', "<$ARGV[0]" )
          or die("Error: cannot open file '$ARGV[0]'\n");

    while (my $line = <sourcefile>){
        chomp $line; #will remove the newline for you.
        $output = $output . $line;
    }
    print $output;
}

main();

Upvotes: 0

Dustin Schaeffer
Dustin Schaeffer

Reputation: 1

Try reading the lines from a filehandle into an array, then joining that array into a string.

open (my $list, "<", $file) or die;
my @lns = <$list>;
chomp @lns;
my $string = join(",", @lns);

print "$string\n";

Upvotes: 0

Hynek -Pichi- Vychodil
Hynek -Pichi- Vychodil

Reputation: 26131

my $list = do {
    use autodie;
    open my $fh, '<', $file;
    chomp(my @lines = <$fh>);
    join ', ', @lines;
};

Upvotes: 1

Related Questions