I am in a learning stage learning about references. I think I have an old fashioned way of doing things and I have a feeling that this example code is good candidate for ''upgrading'' to a more efficient way of hitting the objective. To me, references are new and therefore I feel this could be good learning excercise for those of us that just don't quite understand references, how they work, and what their purpose is.

Merlin helped me some with a paper he wrote for Linux Magazine. However, conceptualization is different from excersization. (:

The objective of this code is to get the number of elements in @var from within multiple sub routines. Is this code optimized or should the use of references make it work more optimally?

The purpose behind this type of example is to keep from repeating lines (in each subroutine) to tell me what the number of elements are in @var. This is why I use subroutines so that I don't have to repeat the same code over and over again.

#!/usr/local/bin/perl -w use strict; &sub1; &sub2; sub sub1 { my @var; my $num; my $numElements; for $num (0..2) { $var[$num] = "blah"; } $numElements = @var; print "Number of elements in \@var of ".(caller(0))[3]." is $numEl +ements\n"; print &eval_array_size(@var),"\n"; } sub sub2 { my @var; my $num; my $numElements; for $num (0..5) { $var[$num] = "blah"; } $numElements = @var; print "Number of elements in \@var of ".(caller(0))[3]." is $numEl +ements\n"; print &eval_array_size(@var),"\n"; } sub eval_array_size { my $numElements = @_; return($numElements); }
TIA guys.

----------
- Jim


In reply to 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.