The <DATA> syntax in perl
Asked Answered
B

2

29

Where can I find more about the following syntax in perl?

The connection between <DATA> and __DATA__ is unclear.

while (my $date_string = <DATA>) {
  chomp($date_string);
  next if not length $date_string;
  print "$date_string ist Unixtime ",
        $lang_date->str2time($date_string),
        " und ",
    $lang_date->time2str( '%d.%m.%Y %T (%Z)',$lang_date->str2time($date_string) ),
        "\n";
}

__DATA__
1.3.1999
1 Marz 1999
1. Marz 1999
1/3/1999
Beitris answered 19/11, 2012 at 22:31 Comment(3)
See official doc perldoc.perl.org/perldata.html and search __DATA__Selene
Fun with __DATA__ handles: https://mcmap.net/q/431141/-how-can-i-use-__data__-twice, https://mcmap.net/q/502226/-writing-a-persistent-perl-scriptEec
Stupid DATA tricksLengthwise
S
35

Quoting the doc:

The __DATA__ token tells the perl compiler that the perl code for compilation is finished.

Everything after the __DATA__ token is available for reading via the filehandle FOOBAR::DATA, where FOOBAR is the name of the current package when the __DATA__ token is reached.

This works just the same as __END__ does in package 'main', but for other modules data after __END__ is not automatically retrievable, whereas data after __DATA__ is.

Can add to this only that using __DATA__ section is quite handy to illustrate some file reading-related concepts in Perl. it's basically a file attached to a code, and contents of this file are easily accessible through <DATA>. That's why it's quite popular here on SO. )

Snobbish answered 19/11, 2012 at 22:33 Comment(0)
T
6

Everything after __DATA__ is treated as a file you can read from the filehandle DATA. DATA is opened automatically and you don't have to do anything to get it that way.

What isn't clear? Your program seems to be using it properly.

Tripodic answered 19/11, 2012 at 22:34 Comment(1)
its not my program, its a peace of code I found on the internets and did not understandBeitris

© 2022 - 2024 — McMap. All rights reserved.