The difference between \ * DATA and * DATA

Whenever I want to simulate input and output to a file descriptor, I often use references to DATA and STDOUT respectively:

 use strict; use warnings; use autodie; #open my $infh, '<', 'infile.txt'; my $infh = \*DATA; #open my $outfh, '>', 'outfile.txt'; my $outfh, \*STDOUT; print $outfh <$infh>; __DATA__ Hello World 

Outputs:

 Hello World 

However, in Borodinโ€™s recent answer , it was demonstrated that in fact there is no need to take the link. Instead, a simple assignment is enough:

 my $infh = *DATA; 

So I created the following script to compare and contrast the difference between these two methods:

 use strict; use warnings; use Fcntl qw(:seek); # Compare Indirect Filehandle Notation my %hash = ( '\*DATA' => \*DATA, '*DATA' => *DATA, ); my $pos = tell DATA; my $fmt = "%-8s %-22s %-7s %s\n"; printf $fmt, qw(Name Value ref() readline()); while ( my ( $name, $fh ) = each %hash ) { seek( $fh, $pos, SEEK_SET ); # Rewind FH chomp( my $line = <$fh> ); printf $fmt, $name, $fh, ref($fh), $line; } __DATA__ Hello World 

Outputs:

 Name Value ref() readline() \*DATA GLOB(0x7fdc43027e70) GLOB Hello World *DATA *main::DATA Hello World 

When it comes to transmitting and reading from a file descriptor, there is no difference between a type character and a type reference.

Switching from testing to a research research form shows the following perldoc pages:

The first link suggests either use. So far, the second gives a list of other alternatives, but mentions how the reference notation is needed if we want to bless the variable. No other difference is proposed.

Is there a functional or preferred style difference between these two indirect file descriptors?

  • my $fh = \*DATA;
  • my $fh = *DATA;
+7
perl
source share
1 answer

One globe; one link to the globe. Most places accept both. Many also accept the name glob as a string, and many accept a reference to an I / O object.

 # Symbolic reference to the glob that contains the IO object. >perl -E"$fh = 'STDOUT'; say $fh 'hi'" hi # Reference to the glob that contains the IO object. >perl -E"$fh = \*STDOUT; say $fh 'hi'" hi # Glob that contains the IO object. >perl -E"$fh = *STDOUT; say $fh 'hi'" hi # Reference to the IO object. >perl -E"$fh = *STDOUT{IO}; say $fh 'hi'" hi 

open(my $fh, '<', ...) populates $fh reference to glob, and it is most supported, so I use it if I need to select.

+9
source share

All Articles