2

I have a file that looks something like this:

hellothisisline1
andthisisline2hi
yepthisistheline

I want to concatenate the lines so that into a single string

hellothisisline1andthisisline2hiyepthisistheline

print "Input file name \n";
open (FILE, <>);
$string = "";
while($line = <FILE>) {
   $string = $string . "" . $line;
}
print "$string \n";

But that didn't seem to work and the output is the file in its original format.

Adrian
  • 9,229
  • 24
  • 74
  • 132
  • Possible duplicate of [What is the best way to slurp a file into a string in Perl?](http://stackoverflow.com/questions/206661/what-is-the-best-way-to-slurp-a-file-into-a-string-in-perl) – Matt Jacob Nov 12 '15 at 00:48
  • $ perl -lne '$all .= $_; END {print $all}' yourfile.txt – AAAfarmclub Aug 20 '20 at 02:22

2 Answers2

1

If you are using Perl5, chomp is useful to remove the newline character at the end of string.

print "Input file name \n";
open (FILE, <>);
$string = ""; 
while($line = <FILE>) {
    chomp($line); # add this line
    $string = $string . "" . $line;
}
print "$string \n";
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
-1

Using the chomp function to remove the newlines. The map applies the chomp function to each line, and the join sticks all the lines together.

print "Input file name \n";
open (FILE, <>);
$string = join('', map { chomp; $_ } <FILE>);
print "$string \n";

Could also use "tr" to delete the newlines after slurping the file:

print "Input file name \n";
open (FILE, <>);
($string = join('', <FILE>)) =~ tr/\n//d;
print "$string \n";
Curt Tilmes
  • 3,035
  • 1
  • 12
  • 24
  • Yes, in general, but chomp needs something to work on.. The map gives the context to read from into $_ which the chomp can work on. You could read into a separate temporary array and chomp that if you wanted... just uglier. – Curt Tilmes Nov 18 '15 at 03:30