Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: Comparing an array with a regex array of strings?

by vinoth.ree (Monsignor)
on Dec 17, 2015 at 05:43 UTC ( #1150582=note: print w/replies, xml ) Need Help??


in reply to Comparing an array with a regex array of strings?

The Following code creates a hash with first column(Person*) as outer key and other values as inner hash, now you can easily go over the outer key and match the Person and get the values.

use strict; use warnings; use Data::Dumper; my %temp=(); my %main_struc=(); my $match='Person2'; while (my $line = <DATA>) { chomp $line; my @fields = split ("," , $line,2); my @temp=split(',',$fields[1]); foreach my $data (@temp){ my($key,$value)=split('=',$data); $key =~ s/^\s+//; $key =~ s/\s+$//; $main_struc{$fields[0]}{$key}=$value } } print Dumper \%main_struc; print "@{$main_struc{$match}}{'Name','Age','Gender'}"

All is well. I learn by answering your questions...

Replies are listed 'Best First'.
Re^2: Comparing an array with a regex array of strings?
by johngg (Canon) on Dec 17, 2015 at 15:24 UTC

    There's no need to strip off leading and trailing spaces if you split using a regex with optional whitespace around your delimiters. I get around the need for a %temp hash by using cascading maps.

    use strict; use warnings; use Data::Dumper; open my $csvFH, q{<}, \ <<EOD or die $!; Person1, Name = Lydia, Age = 20, Gender = F Person2, Name = Carol, Age = 54, Profession = Student, Gender = F, Hei +ght = 4'8 Person3, Name = Andy, Age = 37, Location = USA, Gender = M, Weight = 1 +17 Person4, Name = Nick, Age = 28, Gender = M EOD my %people = map { $_->[ 0 ], { map { split m{\s*=\s*} } split m{\s*,\s*}, $_->[ 1 ] } } map { chomp; [ split m{\s*,\s*}, $_, 2 ] } <$csvFH>; print Data::Dumper->Dumpxs( [ \ %people ], [ qw{ *people } ] );

    I hope this is of interest.

    Cheers,

    JohnGG

Re^2: Comparing an array with a regex array of strings?
by Ppeoc (Beadle) on Dec 19, 2015 at 19:24 UTC
    Thank you! This is a very nice way to do it

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1150582]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (4)
As of 2020-05-29 06:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    If programming languages were movie genres, Perl would be:















    Results (166 votes). Check out past polls.

    Notices?