in reply to Passing a hash byreference to a subroutine

referencing and dereferencing in Perl is used for passing data structures to subroutines. for examples @example is an array to pass it to subroutine

@examples = ('perl', 'linux'); $reference_of_example = \@examples; #referencing your_sub($ref_example); sub your_sub { $ref = @_; print Dumper(@$ref); #@$ref is dereferencing array. }

Replies are listed 'Best First'.
Re^2: Passing a hash byreference to a subroutine
by haukex (Archbishop) on Apr 07, 2017 at 10:07 UTC
    $ref = @_;

    Sorry, but that's not correct, it suffers from the same problem as the OP: it puts the array @_ into scalar context, meaning that $ref will hold the number of elements in @_, instead of its first element as intended. You'd need to write my ($ref) = @_;, as the parentheses on the left side place the right side into list context, and this will cause $ref to be assigned the first element of the array (and the rest of the elements to be ignored in this case).

    Also, this code won't work under strict (also note $reference_of_example vs. $ref_example). When posting code examples, please make sure to test them under strict and warnings.

Re^2: Passing a hash byreference to a subroutine
by thanos1983 (Parson) on Apr 07, 2017 at 10:22 UTC

    Hello karthiknix,

    Sample of your code using strict and warnings as haukex correctly pointed out.

    #!/usr/bin/perl use strict; use warnings; use Data::Dumper qw(Dumper); my @examples = ('perl', 'linux'); my $reference_of_example = \@examples; #referencing print Dumper your_sub($reference_of_example); # prints $VAR1 = 1; print Dumper my_sub($reference_of_example); print Dumper my_solution($reference_of_example); print Dumper haukex_solution($reference_of_example); sub your_sub { my $ref = @_; return $ref; } sub my_sub { return @_; } sub my_solution { my $ref = shift @_; return $ref; # or return shift @_; } sub haukex_solution { my ($ref) = @_; return $ref; } __END__ $ perl test.pl $VAR1 = 1; $VAR1 = [ 'perl', 'linux' ]; $VAR1 = [ 'perl', 'linux' ]; $VAR1 = [ 'perl', 'linux' ];

    Update: Adding haukex solution.

    Hope this helps.

    Seeking for Perl wisdom...on the process of learning...not there...yet!