Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Perl, is there any difference between direct glob aliasing and aliasing via the stash?

In Perl, is there ever any difference between the following two constructs:

*main::foo = *main::bar

and

$main::{foo} = $main::{bar}

They appear to have the same function (aliasing all of the slots in *main::foo to those defined in *main::bar), but I am just wondering if this equivalency always holds.

like image 966
Eric Strom Avatar asked Jul 06 '11 21:07

Eric Strom


2 Answers

Maybe not the kind of difference you were looking for, but there are two big differences between *main::foo and $main::{foo}; the former looks up the glob in the stash at compile time, creating it if necessary, while the latter looks for the glob in the stash at run time, and won't create it.

This may make a difference to anything else poking about in the stash, and it certainly can affect whether you get a used only once warning.

like image 77
ysth Avatar answered Nov 16 '22 02:11

ysth


The following script:

#!/usr/bin/env perl

#mytest.pl

no warnings;


$bar = "this";
@bar = qw/ 1 2 3 4 5 /;
%bar = qw/ key value /;

open bar, '<', 'mytest.pl' or die $!;

sub bar {
    return "Sub defined as 'bar()'";
}
$main::{foo} = $main::{bar};

print "The scalar \$foo holds $foo\n";
print "The array \@foo holds @foo\n";
print "The hash \%foo holds ", %foo, "\n";
my $line = <foo>;
print "The filehandle 'foo' is reads ", $line;
print 'The function foo() replies "', foo(), "\"\n";

Outputs:

The scalar $foo holds this
The array @foo holds 1 2 3 4 5
The hash %foo holds keyvalue
The filehandle 'foo' is reads #!/usr/bin/env perl
The function foo() replies "Sub defined as 'bar()'"

So if *main::foo = *main::bar; doesn't do the same thing as $main::{foo} = $main::{bar};, I'm at a loss as to how to detect a practical difference. ;) However, from a syntax perspective, there may be situations where it's easier to use one method versus another. ...the usual warnings about mucking around in the symbol table always apply.

like image 44
DavidO Avatar answered Nov 16 '22 00:11

DavidO