Writing it like this (using array slice instead of scalar) (deefering an array-reference just to get one element) is bad.

Why? Simple, it looks too complex.

The bottomline is that you should use $array_reference->[index] instead of @array_reference[$index]. If you want more information about references then you shold read: `perldoc perlreftut` and/or `perldoc perlref` and/or `perldoc perldsc`.(updated)

Here is a possible mis-interpretation of the code.


One can think that the array-reference stored in $record[0] is being de-referenced and that that array is printed.

Ofcourse this is impossible, since $record belongs to the foreach loop, so must be a scalar, and therefor $record[0] can never refer to the first element in this 'array', but someone that does not has that much knowledge about Perl might see it that way... (if it would refer to it it has to be $record->[0])

And if you do that, you might be confusing a (new) Perl-user, which is not a good thing...

For the part of wasting memory, I do not think that foreach $record (@x) uses more memory then foreach (@x).

Unfortunally I do not know what happends when this code is executed (that is, what happends internally). But one possibility would be that $record is replaced with the actual variable of @x... (since it is an alias, every modification of $record will modify the element in the array!). This could be implemented in Perl by using a C-pointer, which would mean you are only wasting a few bytes .

Update: Some mis-interpreatations... (a post above confused me by talking about an array slice, which is not correct).


In reply to Re: Using aliases in for loops or not? by Animator
in thread Using aliases in for loops or not? by jkva

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.