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:
search in array

 



balrajswamy
Novice

Dec 15, 2015, 4:56 AM

Post #1 of 5 (1613 views)
search in array Can't Post

Hi All,
Good evening to all.

I have a two arrays. I am new to the Perl.

input:

@aa= qw(a b c d c a b);
@bb= qw(b a c);

Output:

@cc=(a, a, b, c, c);

please help to get expected output in perl

Thanks in advance.

Best regards,
Balrajswamy


Chris Charley
User

Dec 15, 2015, 7:53 AM

Post #2 of 5 (1605 views)
Re: [balrajswamy] search in array [In reply to] Can't Post

I think you wanted 2 'b's in @cc, (because @aa had 2 'b's). If that's so, then the code below gives the result you want.


Code
#!/usr/bin/perl 
use strict;
use warnings;
use Data::Dumper;

my @aa= qw(a b c d c a b);
my @bb= qw(b a c);

my $filter = join "|", @bb;

my @cc = grep /$filter/, sort @aa;

print Dumper \@cc;


The output from Dumper is:


Code
$VAR1 = [ 
'a',
'a',
'b',
'b',
'c',
'c'
];



Laurent_R
Veteran / Moderator

Dec 15, 2015, 10:37 AM

Post #3 of 5 (1599 views)
Re: [balrajswamy] search in array [In reply to] Can't Post

If your data is relatively large, store your second array as a hash and grep values of @aa on the existence of the value in the hash.

Code
my @aa= qw(a b c d c a b); 
my @bb= qw(b a c);
my %bbb = map { $_ => 1} @bb;
print join " ", sort grep { exists $bbb{$_}} @aa; # -> a a b b c c



balrajswamy
Novice

Dec 16, 2015, 2:49 AM

Post #4 of 5 (1588 views)
Re: [Chris Charley] search in array [In reply to] Can't Post

Thanks a lot it is working fine and problem solved.


balrajswamy
Novice

Dec 16, 2015, 2:51 AM

Post #5 of 5 (1587 views)
Re: [Laurent_R] search in array [In reply to] Can't Post

Thanks a lot for solution

 
 


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

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