top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Array iterator count in perl

–1 vote
298 views

If i am iterating through the elements in an array, at any point is it possible to say which element i am handling without using a counter? Are there any built-ins that i can use for it?
ie foreach my $element (a..z) { ... if ( i am the 5th element ) { handle me special } }

posted Aug 8, 2013 by Naveena Garg

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

my $counter = 0;foreach my $e ( a .. z ) { $counter++; if ( $counter == 5 ) { .... }}

answer Aug 8, 2013 by Mandeep Sehgal
Similar Questions
+1 vote
$ perl -le 'system "df -h"'
$ perl -le 'system "df","-h"'

Both two styles work fine. What's the difference between them and which is better usage?

+1 vote

I've a program that needs to print some fields formatted in different ways according to some conditions. The solution I come up is working, but I'm looking for a suggestion for something more elegant.

What I do is something like the following:

print sprintf $formats[ $condition ], @fields;

where $condition is the condition used to select a sprintf format string out of an array (@formats) that contains something like:

my @formats = (
 qw( %09d %-1s %03d ... )
, qw(%-4s %1s %09d %1s %-150s %-4s %011d)
, ...
);

Now, while this approach is working really fine, it is a little hard to decode, especially considering that I've got some formats with 50+ fields. I don't believe that using Perl formats is a solution, it will provide a quite longer configuration (consider I've got even fields specified as "-100%s"!).

Any suggestion to get a more readable code?

0 votes

How can write a python script which will execute some perl scripts in a gui and shouldn't be post processed....?

+1 vote

I'm looking for introductory to advanced examples of RESTful programming in Perl preferably with some good explanations and best practices.

...