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;.


In reply to Re: Print last element using perl reference by kennethk
in thread Print last element using perl reference by gobisankar

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.