Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Comparing the first element of an array with an array

by lampros21_7 (Scribe)
on Jul 28, 2005 at 13:30 UTC ( [id://478960]=perlquestion: print w/replies, xml ) Need Help??

lampros21_7 has asked for the wisdom of the Perl Monks concerning the following question:

Hi, i want to check if the first element of an array exists in the whole of another array. The first element is say $links[0] and the other array is @visited_urls. Sorry, for asking such a (probably) trivial question but i ve been looking through super search and can't find anything. Thanks

Replies are listed 'Best First'.
Re: Comparing the first element of an array with an array
by holli (Abbot) on Jul 28, 2005 at 13:33 UTC
    @found_urls = grep { $_ eq $links[0] } @visited_urls;


    holli, /regexed monk/
Re: Comparing the first element of an array with an array
by sh1tn (Priest) on Jul 28, 2005 at 13:42 UTC
    @urls{@visited_urls} = (); exists $urls{$links[0]} and print "found\n";


Re: Comparing the first element of an array with an array
by Zed_Lopez (Chaplain) on Jul 28, 2005 at 17:37 UTC
    use List::Util qw(first); $links0_in_visited_urls = first { $_ eq $links[0] } @visited_urls
Re: Comparing the first element of an array with an array
by lampros21_7 (Scribe) on Jul 29, 2005 at 00:09 UTC
    Apologies for this but i need this in an if statement so that if the URL already exists in the array then do something. The methods you have given me put the URL in another array which i dont really want and i dont think the statemnts you give me can be used in an if statement. Thanks for your patience
      Grep returns the numer of items the code was true for when called in scalar context, so you can pretty much just use holli's code in an if statment
      if ((grep {$_ eq $links[0] } @visited_urls) > 0) { print "URL found\n"; } else { print "URL not found\n"; }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://478960]
Approved by Tanalis
Front-paged by planetscape
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (3)
As of 2024-03-28 18:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found