Search code examples
perlsafefilehandle

Using perl __DATA__ assign its value to variable


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

Solution

  • 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