Ratna_Ranjan has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks

I want to pass an array into a subroutine and dereference it and print it in a particular format.Below is the code that I tried.

But the error i get is Gobal symbol "$sample" requires explicit package name at deref.pl line 9.

can someone plz explain me what is wrong in my code??and how to dereference the array and print the array elements with a tab between them??

#!/usr/bin/perl use strict; my @sample=qw(a,b,c); &trial(\@sample); sub trial { @sample=@_; print join("\t",@$sample); }

Replies are listed 'Best First'.
Re: dereferencing array in a subroutine
by toolic (Bishop) on Oct 28, 2009 at 17:56 UTC
    Here is an annotated version of your code to try and demonstrate the issue:
    #!/usr/bin/perl use strict; # Great start! my @sample=qw(a,b,c); # Declare array variable &trial(\@sample); # Pass array as a reference to sub sub trial { @sample=@_; # Clobber the contents of your origina +l array # setting the original array to the co +ntents # of the special array (@_), which jus +t has # a reference print join("\t",@$sample); # Try to dereference a scalar variable + named # 'sample', which you never declared. }

    use strict and warnings... warnings would also show another issue with your use of qw. Here is an improved version:

    #!/usr/bin/perl use strict; use warnings; my @sample = qw(a b c); trial(\@sample); sub trial { my ($aref) = @_; print join "\t", @{ $aref }; }

    See also References quick reference

Re: dereferencing array in a subroutine
by almut (Canon) on Oct 28, 2009 at 17:46 UTC
    ... my @sample=qw(a b c); trial(\@sample); sub trial { my ($sample) = @_; print join("\t",@$sample); }

    This would assign the array reference passed to the routine to the reference $sample (a local lexical scalar variable), which you can then dereference to an array using @$sample.