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

Dear friends, I am doing a simple exercise using perl array reference. I want to print last element in the array using reference values. code which i written is given below

#!/usr/bin/perl @arr_val=(1,2,3,4,5,6,7,8); $arr_ref=\@arr_val; print $$arr_ref[-1]; print "\n"; print $$arr_ref[@$arr_ref-1]; print "\n"; print $#arr_val; print "\n"; print $#arr_ref;

Actually my doubt here is print $#arr_val is printing 7, at the same time print $#arr_ref is printing -1. What i have to do if i want to get last index i.e 7 using perl reference with the same method like $#arr_val.

Replies are listed 'Best First'.
Re: Print last element using perl reference
by kennethk (Abbot) on Apr 29, 2010 at 15:49 UTC
    This is a situation where strictures would have been useful for you. If you run your posted code with strict, Perl gives you the error:

    Global symbol "@arr_ref" requires explicit package name at fluff.pl li +ne 12. Execution of fluff.pl aborted due to compilation errors.
    When you write #arr_ref, Perl examines the array @arr_ref, which you never defined. Since it is not defined, its highest index is -1. The expression you intended is likely $#$arr_ref, which returns 7 as desired. The following code does what I assume you intended, with strict and warnings thrown in for good measure:

    #!/usr/bin/perl use strict; use warnings; my @arr_val=(1,2,3,4,5,6,7,8); my $arr_ref=\@arr_val; print $$arr_ref[-1]; print "\n"; print $$arr_ref[@$arr_ref-1]; print "\n"; print $#arr_val; print "\n"; print $#$arr_ref;

    See perfreftut or perfref for more information on references, and see Use strict warnings and diagnostics or die for a howto and why for use strict; use warnings;.

Re: Print last element using perl reference
by moritz (Cardinal) on Apr 29, 2010 at 15:42 UTC

      Thanks friends

Re: Print last element using perl reference
by ikegami (Patriarch) on Apr 29, 2010 at 15:53 UTC

    at the same time print $#arr_ref is printing -1.

    Of course. You never put anything in @arr_ref. Start by using use strict; use warnings;.

    @array -> @$ref or @{$ref}
    so
    $#array -> $#$ref or $#{$ref}
Re: Print last element using perl reference
by pemungkah (Priest) on Apr 29, 2010 at 18:44 UTC
    And of course the last actual value is $arr_ref->[-1].