Question

I am having problems doing this:

$contents = do { local $/;  <SEQ> };
$contents =~ "s/\n/ /g";
print $contents;

I want to join all lines of a file into one. However, it doesn't work...

Any idea what's happening with my code?

Thank you.

Was it helpful?

Solution 3

You can use File::Slurp module:

use File::Slurp qw/read_file/;
my $text = read_file( 'filename' ) ;
$text =~ s/\n/ /g;
print $text;

If you don't want to use the module, you can try this:

#!/usr/bin/perl

use strict;
use warnings;

my $text;
open my $fh, "<", "./alarm.pl" or die $!;
{
    local $/;                   # enable localized slurp mode
    $text = <$fh>;
}
close $fh;

$text =~ s/\n/ /g;
print $text;

OTHER TIPS

remove the quote marks around the regexp

$contents = do { local $/;  <SEQ> };
$contents =~ s/\n/ /g;
print $contents;

The easiest way is probably Perl6::Slurp module:

use Perl6::Slurp;
$contents = slurp \*SEQ;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top