If I understand the point of your question, you want to know how you can pass an array to a subroutine using references and still do array-ish things with it.

As I'm sure you're aware, the eval_array_size() routine in your example receives the contents of @var as a list of individual arguments. There are two ways to convert this to passing @var through a reference:

You can explicitly take a reference and pass that as a scalar value:

print "\@var has ", eval_array_size(\@var), " elements.\n"; sub eval_array_size { my $aref = shift; return scalar @{$aref}; }
Note I'm using "scalar" to force the sub to return the number of elements, instead of (possibly) returning the array contents.

The second way is to prototype the function. For this to work, the function has to appear before it's called:

sub eval_array_size (\@) { my $aref = shift; return scalar @{$aref}; } print "\@var has ", eval_array_size(@var), " elements.\n";
Here, perl will require that the function's argument be an actual array (e.g. a list of items in parentheses wouldn't be acceptable) and will automatically reference the array for you. This second method is generally used for making functions that "act" like built-in commands.

In reply to Re: Change this example to use references... by kjherron
in thread Change this example to use references... by snafu

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.