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

Hi all, i have the following code to remove empty lines:
my @data; open(FILE, "<$filename"); foreach(<FILE>){ push @data,$_ unless ($_ eq "\n"); } close FILE;
now what i would like to do is put the contents of @data in to a 1 line string so that
xxxxxxx xxxxxxxx xxxxxxxxx xxxxxx
becomes
xxxxxxx xxxxxxxx xxxxxxxxx xxxxxx
ive tried and tried but just cant do it :/

Replies are listed 'Best First'.
Re: read file into 1 line string
by davido (Cardinal) on Apr 21, 2012 at 15:31 UTC

    A self-contained solution that leaves no footprint or side-effects behind. ...all that comes out of the do{...} block is the result you seek.

    my $data = do{ open my $file, '<', $filename or die $!; local $/ = undef; local $_ = <$file>; s/\n+/ /g; $_; };

    Dave

Re: read file into 1 line string
by hperange (Beadle) on Apr 21, 2012 at 12:47 UTC
    Hi, I would use something like this:
    #!/usr/bin/perl use strict; use warnings; open(my $fh, '<', "test") or die("Could not open file: $!\n"); my @lines; while (<$fh>) { next if $_ eq "\n"; s/\n/ /; push @lines, $_; } my $long_line = join('', @lines); print $long_line, "\n";
Re: read file into 1 line string
by stevieb (Canon) on Apr 21, 2012 at 13:22 UTC

    Bit of a different way:

    open my $fh, '<', $filename or die "Can't open file: $!"; my $line = do { local $/; <$fh> }; $line =~ s/\n*\n/ /g;

    There's also File::Slurp.

    Edit: changed \n?\n to \n*\n to catch multiple consecutive blank lines.

      my $line = do { local $/; <$fh> }; $line =~ s/\n*\n/ /g;

      Or:

      my $line = do { local $/; <$fh> }; $line =~ tr/\n/ /s;

      Or just:

      ( my $line = do { local $/; <$fh> } ) =~ tr/\n/ /s;
Re: read file into 1 line string
by tommyxd (Acolyte) on Apr 21, 2012 at 12:13 UTC
    You can try doing something like this:
    #!/usr/bin/perl -w use strict; my @data = ("something", "else\n", "and", "again\n", "hi"); my $result; for (@data) { chomp; $result .= $_ . " "; } print $result;
Re: read file into 1 line string
by trizen (Hermit) on Apr 21, 2012 at 14:24 UTC
    my $string = do { local @ARGV = $filename; join q{ }, grep $_ ne "\n" && chomp, <>; };
      Nice solution :)

      Althrough I think it would not give the desired output for an input file like this:

      xxxxxxx xxxxxxxx xxxxxxxxx xxxxxx
A reply falls below the community's threshold of quality. You may see it by logging in.