Can I name an anonymous array in Perl?

后端 未结 4 531
野趣味
野趣味 2021-01-13 05:06
#!/usr/bin/perl -w

use strict;

my $aref = [1, 2, 3];
my @a = @$aref;              # this line
$a[1] = 99;
print \"aref = @$aref\\n\";
print \"a = @a\\n\";
<         


        
相关标签:
4条回答
  • 2021-01-13 05:52

    I wonder why would you want to do this? I presume it's a performance issue, but the usual solution is to pass your data around by reference. It is just as easy to write $aref->[1] as $a[1]

    You could alias your reference in the package symbol table by assigning to the typeglob, but the alias must be a package variable

    use strict;
    use warnings;
    
    my $aref = [1, 2, 3];
    
    our @a;
    *a = $aref;
    
    $a[1] = 99;
    
    print "aref = @$aref\n";
    print "a    = @a\n";
    

    output

    aref = 1 99 3
    a    = 1 99 3
    

    There are a number of modules that offer a nice syntax and allow you to alias lexical variables

    Here's a version that uses Lexical::Alias which has the advantage of aliasing lexical variables, and could be more robust than assigning to typeglobs. Data::Alias works in a very similar way. The output is identical to the above

    use strict;
    use warnings;
    
    use Lexical::Alias qw/ alias_r /;
    
    my $aref = [1, 2, 3];
    
    alias_r $aref, \my @a;
    
    $a[1] = 99;
    
    print "aref = @$aref\n";
    print "a    = @a\n";
    

    an alternative way is to use alias instead of alias_r with

    alias @$aref, my @a;
    
    0 讨论(0)
  • 2021-01-13 06:00
    1. our @array; local *array = $aref;
      

      Pros: Built-in feature since 5.6.
      Cons: Ugly. Uses a global variable, so the variable is seen by called subs.

    2. use Data::Alias qw( alias );
      alias my @array = @$aref;
      

      Pros: Clean.
      Cons: This module gets broken by just about every Perl release (though it gets fixed quickly if not before the actual release).

    3. use feature qw( refaliasing );
      no warnings qw( experimental::refaliasing );
      \my @array = $aref;
      

      Pros: Built-in feature.
      Cons: Requires Perl 5.22+, and even then, the feature is experimental.

    0 讨论(0)
  • 2021-01-13 06:04

    One option is to use the Data::Alias package from CPAN.

    This way you can write:

    #!/usr/bin/perl
    
    use Data::Alias qw( alias );
    
    my $aref  = [1, 2, 3];
    
    alias my @a = @$aref;
    
    $a[1] = 99;
    print "aref = @$aref\n";
    print "a = @a\n";
    

    A related question on SO can be found here: Assign address of one array to another in Perl possible?

    0 讨论(0)
  • 2021-01-13 06:09

    To expand on Borodin's answer, I've tested this with the Lexical::Alias module:

    #!/usr/bin/perl -w
    
    use strict;
    use Lexical::Alias 'alias_a';
    
    my $aref = [1, 2, 3];
    my @a;
    alias_a(@$aref, @a);
    $a[1] = 99;
    print "aref = @$aref\n";
    print "a = @a\n";
    
    0 讨论(0)
提交回复
热议问题