Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

How do i read each line of the file into string?

by anjaana78 (Novice)
on May 09, 2001 at 17:28 UTC ( [id://79069]=perlquestion: print w/replies, xml ) Need Help??

anjaana78 has asked for the wisdom of the Perl Monks concerning the following question:

I have a text file that has one word per line.... now i have to read that file into a string and also add a comma after each word. for example the text file is gonna look something like this... tariq rashid mike mushi and i have to get the output something like this tariq, rashid, mike, mushi thanks for your help in advance....
  • Comment on How do i read each line of the file into string?

Replies are listed 'Best First'.
Re: How do i read each line of the file into string?
by alfie (Pilgrim) on May 09, 2001 at 17:50 UTC
    open (FILE, "<my_file") || die "can't open my_file: $!"; my @stuff = <FILE>; # get whole file into array close(FILE); chomp @stuff; # cut out trailing newlines my $string = join(', ', @stuff); # join to one string undef @stuff; # clean up behind us
Re: How do i read each line of the file into string?
by koolade (Pilgrim) on May 09, 2001 at 17:39 UTC
    my $string; # Open the file open(FILE, "$file_name") or die "could not open $file_name : $!"; # Iterate over each line of the file while (<FILE>) { # Take off trailing newline chomp; # Append line and comma to the string $string .= "$_,"; } # Close the file close(FILE); # Chop off trailing comma chop $string;
Re: How do i read each line of the file into string?
by knobunc (Pilgrim) on May 09, 2001 at 18:35 UTC
    use IO::File; my $fh = IO::File->new("<$filename") or die "Unable to open $filename: $!"; my $string = join(", ", map({ chomp; $_ } $fh->getlines) ); $fh->close;
Re: How do i read each line of the file into string?
by jeroenes (Priest) on May 10, 2001 at 19:27 UTC
    If you have enough RAM:
    undef $/; $file = <>; s/\s*\n/,/s; #catches spaces as well. print;
    If not:
    chomp; print; print ',' while ( <> );
    (I didn't worry about trailing comma's)

    Jeroen
    "We are not alone"(FZ)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://79069]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (3)
As of 2024-04-24 20:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found