-1

I am trying to use the filehandle DATA in a script, assign the values to a variable, and when it prints it just prints and empty string.

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper qw(Dumper);  
my $str = <DATA> ;
print "$str\n" ;

__DATA__
ab cd ef gh ij
Cœur
  • 37,241
  • 25
  • 195
  • 267
capser
  • 2,442
  • 5
  • 42
  • 74
  • 2
    That code prints `ab cd ef gh ij` (followed by two line feeds), not "an empty string". – ikegami Jun 20 '19 at 21:08
  • yes it does - I have no idea what happened before. – capser Jun 20 '19 at 21:18
  • It's possible that you had an extra blank line after `__DATA__` before the line `ab cd ef gh ij` in your original code that was producing the problem you're describing. Since you are reading from `` in scalar context without manipulating `$/`, you are only getting the first line of data. If that first line happened to be empty, you would see no visible output other than some blank lines. – DavidO Jun 20 '19 at 21:46

1 Answers1

2

If you have more than one line in __DATA__, you might want to use "slurp" (read the entire content of <DATA> into a variable):

my $str = do { local $/ = undef; <DATA> };
print "$str\n";
__DATA__
ab cd
ef gh
i
j
truth
  • 1,156
  • 7
  • 14