CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
VERY SIMPLE QUESTION FOR MOST...

 



mattmatt
Deleted

Jun 25, 2000, 9:47 PM

Post #1 of 5 (544 views)
VERY SIMPLE QUESTION FOR MOST... Can't Post

ok, i am trying to get a match from an array

i have an array @names, and someone enters their name in a text field, i want it to where if they enter a name thats already in the array @names, itll give them an error message, but if its not, itll go ahead and finish running the script
please help
thanx!


japhy
Enthusiast

Jun 26, 2000, 6:44 AM

Post #2 of 5 (544 views)
Re: VERY SIMPLE QUESTION FOR MOST... [In reply to] Can't Post

A hash is the best way to do this, not an array.

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>


{
my %hash;
@hash{@array} = ();
$found = exists $hash{$some_element};
}
</pre><HR></BLOCKQUOTE>

You can not use a regular expression on an array, and in this case, you wouldn't want to, anyway. You want an exact match. You wouldn't want to use grep() either, since that won't stop until it's gone through the entire array. A for loop is a good option, too, but if you're going to be checking a lot, use a hash instead of (or along with) an array.

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>


for (@elements) {
$found = 1, last if $_ eq $some_element;
}
</pre><HR></BLOCKQUOTE>


mattmatt
Deleted

Jun 26, 2000, 7:14 AM

Post #3 of 5 (544 views)
Re: VERY SIMPLE QUESTION FOR MOST... [In reply to] Can't Post

thank you VERY much!!!


mwaf
Deleted

Jun 26, 2000, 10:43 AM

Post #4 of 5 (544 views)
Re: VERY SIMPLE QUESTION FOR MOST... [In reply to] Can't Post

if (@names =~ /name/) { print "error"; }
else { the rest of the script }

this should work (however, I've never tried this with an array)

If the script is long and you don't want that else there you can put " die " infront of print or " exit; " after print.



Kanji
User / Moderator

Jun 26, 2000, 10:50 AM

Post #5 of 5 (544 views)
Re: VERY SIMPLE QUESTION FOR MOST... [In reply to] Can't Post

Pick your poison...
<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>

foreach my $name (@names) {
die "$entered_name already in \@names"
if $name eq $entered_name;
}</pre><HR></BLOCKQUOTE>
<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>

die "$entered_name already in \@names"
if grep { $_ eq $entered_name } @names;</pre><HR></BLOCKQUOTE>
<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>

%names = map { $_, 1 } @names;
die "$entered_name already in \@names" if $names{$entered_name};</pre><HR></BLOCKQUOTE>

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives