in reply to Simple iteration problem

++Moritz and Anonymonk and toolic for encouraging good programming. I learned the hard way to always use strict; use warnings;. This will help Perl help you catch your own errors.

update: toolic and Eimi Metamorphoumai have pointed out that much of my concern about @tab was for nought.

<blockignore quality="sheepish">
I think there's one more thing to comment on in your code. The value of @tab is the number of elements in the array. I personally think that toolic's output is more helpful and is certainly more instructive, but if you really wanted the number of elements in the array, you'd have gotten:

1 3 2
for toolic's results, since that's the number of elements in the arrays on the lines that satisfy the conditional.

If you wanted to print the array instead of either the first element of the array or the number of elements, print takes a list and you can cast @tab into a list as:
   print (@tab,"\n");

When I did this it jammed the elements of the array all together as:

3 567 109
and I solved that with:
   print join(' ',@tab,"\n");
</blockignore>

Finally, just for fun I turned it into a one-liner. This risks encouraging some bad programming (I didn't use strictures in my one liner), but it takes advantage of several things. perl -n replaces the outer while (<TAB>) loop. perl -a automatically spilts it for you into an array, @F. perl -l automatically handldes the newline when printing. This was on Win32, so your delimeters may vary (YDMV?).

C:\chas_sandbox>type test653837.txt 3 5 6 7 2 22 222 10 9 C:\chas_sandbox>perl -lane "$seed = 1.04 unless $seed;$diff=$F[0]-$see +d;if ($dif f>=0.1) {print join(' ',@F);$seed=$F[0];}" test653837.txt 3 5 6 7 10 9


I humbly seek wisdom.

Replies are listed 'Best First'.
Re^2: Simple iteration problem
by toolic (Bishop) on Nov 29, 2007 at 17:11 UTC
    print join(' ',@tab,"\n");
    There is no need to use join in this case. This will accomplish the same thing:
    print "@tab\n";
    When interpolating an array inside double-quotes, the value of the $" special variable is used to separate elements of the array. The default value of $" is a single space. See perlvar, and search for LIST_SEPARATOR.
Re^2: Simple iteration problem
by Eimi Metamorphoumai (Deacon) on Nov 29, 2007 at 17:16 UTC
    Actually, @tab inside a string interpolates to the contents of the array, separated by $" (a single space by default). For instance,
    my @tab = (3,7); print "@tab\n";
    will print "3 7". Try it yourself.