in reply to check if an element exists in array

Is the order of the lines meaningfull?
If not you could use a hash which holds an array with all the values:

my %people; while( my $line = <IN> ) { my ($name, $value) = split /\s+/, $line; if (!exists $people{$name}) { $people{$name} = [ $value ]; # store array with one value } else { push @{$people{$name}}, $value; # push 2nd,3rd,.. value on arr +ay } }
The %people hash would then look like:
%people = ( 'Andreas' => [ '27' ], 'John' => [ '15' ], 'Andrew' => [ '34' ], 'Jim' => [ '12', '57' ], 'Peter' => [ '08' ] );
This preserves the order of the values but not the order of the names.

Replies are listed 'Best First'.
Re^2: check if an element exists in array
by johngg (Canon) on Apr 19, 2008 at 11:30 UTC
    You can save yourself some typing as Perl will auto-vivify the anonymous array for you if it doesn't exist already. Your

    if (!exists $people{$name}) { $people{$name} = [ $value ]; # store array with one value } else { push @{$people{$name}}, $value; # push 2nd,3rd,.. value on arr +ay }

    can become

    push @{$people{$name}}, $value;

    I hope this is of interest.

    Cheers,

    JohnGG