Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

Re: Counting in loop help!

by Rudolf (Pilgrim)
on Jul 26, 2012 at 19:53 UTC ( #983923=note: print w/replies, xml ) Need Help??

in reply to Counting in loop help!

Im not sure I fully understand your question, but I will try to answer it. I'm not sure why your using a list down in check_names to get your argument. but anyway I would just use counter, if you want to incorporate it into the for loop perhaps or you can put it outside..

my $how_many_names_total = 0; foreach my $name(@names){ if($name){ $how_many_names_total++; check_names($name); } else{ next; } }

Replies are listed 'Best First'.
Re^2: Counting in loop help!
by Anonymous Monk on Jul 26, 2012 at 20:01 UTC
    The count has to be done from the check_names sub, the way you did its OK but the trick part is to capture the last time the check_names sub was called inside of it.

      is it possible you can remove the invalid names before going through the list? for example create a new array with the valid names.. find the number of them and then test the id against the array element in your subroutine:

      my @raw_names = ...; my @valid_names = (); my $total_valid_names = -1; foreach my $raw_name(@raw_names){ next unless $raw_name; push(@valid_names,$raw_name); $total_names++; } for(my $i=0;$i<length(@valid_names);$i++){ check_name($valid_names[$i],$i); } sub check_names{ my($name,$id) = @_; if($id == $total_valid_names){ say "$name is the last name! ($idth)"; } }

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://983923]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (6)
As of 2018-06-25 10:06 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (126 votes). Check out past polls.