On Sat, Nov 15, 2003 at 11:33:15PM -0800, Paul Harwood wrote: > I am trying to push an element into a nested array, but ONLY if it > doesn't already exist.
A question of this nature usually suggests that you should be using a hash instead of an array. > I thought the best way to do this might be the > code I wrote below but it doesn't work. > > @{$names{TEST}} = ('Paul', 'Mike'); > print "Arrays is: "; > print @{$names{TEST}}; > print "\n"; > $another_name = "George"; > push @{$names{TEST}}, $another_name unless grep ($another_name, Here is the problem. You are only checking whether $another_name name is true, and since it always is you never do the push. You need grep ($_ eq $another_name, > @{$names{TEST}}); # This is the part not working. > print "Arrays is now: "; > print @{$names{TEST}}; > > > I thought that the $another_name scalar would be pushed once a grep of > the nested array shows that it doesn't already exist. How can I make > this work? And here is the hash solution which you may find useful. How the hash is initialised is not important. The important thing is that $names{TEST} is now a hash, whose keys represent the names and whose values are irrelevant. #!perl -l @{$names{TEST}}{qw( Paul Mike )} = (); print "Arrays is: ", sort keys %{$names{TEST}}; $another_name = "George"; $names{TEST}{$another_name}++; print "Arrays is now: ", sort keys %{$names{TEST}}; Thank you for posing the question well. You told us what you wanted to do, showed us exactly how you tried to do it and told us how it didn't do what you expected. That makes it easy to answer. -- Paul Johnson - [EMAIL PROTECTED] http://www.pjcj.net -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]