Hello slugman, welcome to the Monastery!

The code you posted has a number of issues:

my @a; ... my $na; my $Na; $na = $#a; $Na = ( 0, 1..$na ); @a = ...; for my $i (@Na)...

$Na needs to be @Na here. However, even when this is fixed the code can never work as you want, because $na is initialised before @a is populated, so it will always be 0. The simplest solution is to forego both these variables and code the loop directly:

for my $i (0 .. $#a)

Update: And in the assignment to @a, the elements /, /home, etc. are strings which need to be quoted.

In fact, the whole code snippet can benefit greatly from being simplified:

use strict; use warnings; my @a = qw( / /home /var /tmp /var/tmp ); my @b; $b[$_] = `ls $a[$_]` for (0 .. $#a); for my $i (0 .. $#a) { my @c = split("\n", $b[$i]); printf("%s%s%s\n\n", $a[$i], ($i ? '/' : ''), $c[$_]) for (0 .. $# +c); }

This does what (I think) you want, in about half the lines and using only 4 variables. Yes, it may appear cryptic due to its heavy use of Perl idioms — but these idioms are well worth learning, as they make the code simpler (and, the simpler the code, the easier it is to debug and maintain).

The loop controls next, last, and redo are often useful, but in this case the ternary operator ? : seems a better fit to the task at hand. (I see aaron_baugher got in ahead of me on this one.)

HTH,

Athanasius <°(((><contra mundum


In reply to Re: Loop Control by Athanasius
in thread Loop Control by slugman

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.