mikedoorhandle
mikedoorhandle

Reputation: 33

Using a variable as a hash key Perl 5.32

I am reading user IDs from a csv file and trying to check if that user ID exists in my hash, however I have found that my checking through if(exists($myUserIDs{"$userID"})) is never returning true, despite testing with multiple keys that are in my hash.

open $file, "<", "test.csv";
while(<$file>)
{
    chomp;
    @fields = split /,/, $_;
    $userID = @fields[1];
    
    if(exists($myUserIDs{"$userID"}))
    {
        #do something
    }
}

Upvotes: 1

Views: 97

Answers (2)

vkk05
vkk05

Reputation: 3222

See if this works for you.

use strict; use warnings;
use Data::Dumper;

my (%myUserIDs, @fields);
%myUserIDs = (
                '1' => 'A',
                '4' => 'D'
            );

print Dumper(\%myUserIDs);

while(<DATA>)
{
    chomp;
    @fields = split /,/, $_;
    my $userID = $fields[1];
    
    if(exists($myUserIDs{$userID})){
        print "ID:$userID exists in Hash\n";
    } else {
        print "ID:$userID not exists in Hash\n";
    }
}

__DATA__
A,1
B,2
C,3

Output:

$VAR1 = {
          '4' => 'D',
          '1' => 'A'
        };
ID:1 exists in Hash
ID:2 not exists in Hash
ID:3 not exists in Hash

Upvotes: 0

mikedoorhandle
mikedoorhandle

Reputation: 33

Turns out I wrote my test csv file with spaces after each comma. Like 1, 2, 3 instead of 1,2,3 so my keys weren't actually matching. There goes an hour of my time haha.

Upvotes: 2

Related Questions