How to use the __DATA__ descriptor if the file name is not specified in perl

Look for a method using the DATA descriptor if the file name is not specified in the perl script.

I am not very good at perl.

Sort of:

use strict; use warnings; use autodie; use diagnostics; my $fd; if( $ARGV[0] && -f $ARGV[0] ) { open $fd, "<", $ARGV[0]; } else { $fd = "DATA"; #what here? } process($fd); close($fd); #closing the file - or the DATA handle too? sub process { my $handle = shift; while(<$handle>) { chomp; print $_,"\n"; } } __DATA__ default content 
+4
source share
2 answers

$fd=\*DATA ; gotta do the trick

+5
source

You may prefer the default DATA descriptor if the file opens with an error instead of letting autodie stop your program. This is a better test anyway than -f . Something like this is possible

 my $fd = \*DATA; if (@ARGV) { if (open $_, '<', $ARGV[0]) { $fd = $_; } else { warn qq{Unable to open "$ARGV[0]" for reading: $!}; } } 
+1
source

Source: https://habr.com/ru/post/1479323/


All Articles