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:
How to turn this into a hash

 



regex2012
User

Feb 22, 2016, 9:30 AM

Post #1 of 4 (1255 views)
How to turn this into a hash Can't Post

I have this


my @typedefs = qw(do antenna bar me do);
my @a =qw(do455 me bug car);


foreach my $line (@a) {
foreach my $line1 (@typedefs) {
if ($line =~ /$line1/) {

print "$line\n"; # perform various actions here if line match
}
}
}

Code
It gives: 
do455
do455
me


This works but I want to do two things.
1. Can this be made into a search using a hash instead?
2. When it prints out, it prints do455 twice instead of once. Can it be made to print one do455 only?


Laurent_R
Veteran / Moderator

Feb 22, 2016, 10:15 AM

Post #2 of 4 (1249 views)
Re: [regex2012] How to turn this into a hash [In reply to] Can't Post

If you're happy with exact match, then, yes, you can have a hash lookup, it'll be faster and easier. But you are using regex match in your code; if that's really what you need, then hash lookup won't work, as hash lookup can only work with exact match.


Laurent_R
Veteran / Moderator

Feb 22, 2016, 10:35 AM

Post #3 of 4 (1246 views)
Re: [regex2012] How to turn this into a hash [In reply to] Can't Post

An example with a hash lookup:


Code
my %typedefs = map { $_ => 1 } qw(do antenna bar me do); 
my @a =qw(do455 me bug car);


foreach my $line (@a) {
print $line if exists $typedefs{$line};
}


But, as I said earlier, this works only for exact match. And it seems that you are really looking for regex matches. This won't work for regex matches.


Laurent_R
Veteran / Moderator

Feb 22, 2016, 10:45 AM

Post #4 of 4 (1245 views)
Re: [regex2012] How to turn this into a hash [In reply to] Can't Post

As for your "do455" being printed twice, the simplest way if to remove duplicates from @typedefs before you start. The easiest way to remove duplicates might be to use a temporary hash:


Code
my %hash = map { $_ => 1 } qw(do antenna bar me do);  
my @typedefs = keys %hash;


After that, the @typedefs array contains:

Code
   0  'bar' 
1 'me'
2 'do'
3 'antenna'

so the "do" duplicate has been removed.

You might also use the List::MoreUtils uniq function: http://search.cpan.org/~rehsack/List-MoreUtils-0.413/lib/List/MoreUtils.pm#uniq_LIST

 
 


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

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