Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

foreach loop ...

Status
Not open for further replies.

PerlIsGood

Programmer
Jan 24, 2002
154
US
Below I've posted code block from a script I whipped up to show the number of messageboard users currently online. I just can't seem to get my head wrapped around why this isn't working the way I want :)
Code:
open FILE, "./directory/memberlist.txt" or die "Couldn't open file: $!";
@members = <FILE>;
close FILE;

$whoson = 0;

#@online contains info from log.txt file (who's on now)
#log.txt tracks all hits, so check against memberlist
#and increment $whoson if match found
foreach ( @online ) {
    ( $user, $time ) = split ( /\|/, $_ );
    foreach ( @members ) {
        if ( $_ eq $user ) { $whoson++; }
    }
}

print qq~<b><u>Members Online:</u></b>   $whoson</font>\n~;

This is really driving me nuts cause the code doesn't cause any errors, it just always produces 0, no matter who's logged in or not. So I guess I can assume it's not finding a match in the nested foreach, or its just skipping that altogether... :/

I've tested @online and @members individually to make sure they're at least holding values. Any help...?
 
Thx! Using chomp @message gave me the number of elements (confused by that), but using chomp on the control variable worked like a charm!
Code:
foreach ( @online ) {
    ( $user, $time ) = split ( /\|/,$_ );
    foreach ( @members ) {
        chomp;
        if ( $_ eq $user ) { $whoson++; }
    }
}
 
chomp removes the value corresponding to $/ which is the input record separator from the end of a variable or if a list is supplied then from each element in the list or if a hash is supplied then from each value. It returns the number of characters removed this way. You were reading in the file lines and they end with a \n which caused your matching problems. Let me tell you the number of times I have forgotten about that.

Hope This Helps,
Johnny
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top