in reply to Multiple File handling and merging records from 2 files
Instead of a HoH, of course another way is a HoA. This idea can more closely follow your input data format as csv files. Which is better, is debatable.#!/usr/bin/perl use strict; use warnings; use Data::Dumper; ## This shows that if you test a multi-dimensional hash, ## Perl will "auto-vivify" the first dimension in the ## process of checking if the 2nd dimension exists. my %apps; $apps{"App1"}{Memory} = 4; $apps{"App1"}{Language} = 'Perl'; $apps{"App1"}{CPU} = '1.4'; $apps{"App1"}{Cores} = '2'; print "No App8 Cores\n" if !exists $apps{App8}{Cores}; print Dumper \%apps; __END__ No App8 Cores $VAR1 = { 'App8' => {}, <-- the exists() created this!!! 'App1' => { 'Memory' => 4, 'Cores' => '2', 'Language' => 'Perl', 'CPU' => '1.4' } };
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; use Data::Dump qw/pp/; use constant { MEMORY => 0, LANGUAGE => 1, CPU => 2, CORES => 3, }; my $file1 =<<FILE1; App1, 4 Perl App2 8 Java App3 ,8 Java App4,4 PHP App5 8 C# FILE1 my $file2 =<<FILE2; App1,1.5 2 App2 2.5 4 App3 2.8 4 App4 2.8 2 App5 2.8 2 FILE2 my %apps; # There is certainly some error handling code missing # but an obvious way to make a Hash of Array from these 2 files # that maintains a "csv" array presentation... open my $file, '<', \$file1 or die "$!"; while (my $line = <$file>) { my ($app, @tokens) = split /[,\s]+/,$line; push @{$apps{$app}},@tokens } open $file, '<', \$file2 or die "$!"; while (my $line = <$file>) { my ($app, @tokens) = split /[,\s]+/,$line; push @{$apps{$app}},@tokens } close $file; # Op's requirement: # Need to print name of apps that have CPU value 2, sorted by their # memory size e.g App1, App4 and App5 # pp \%apps; ### UNCOMMENT this to see the Hash of Array # filter using grep to find the apps that use only 2 CORES my @core2Apps = grep{$apps{$_}[CORES]==2} keys %apps; # Now sort the results my @sortedAppsbyMemory = sort{$apps{$a}[MEMORY] <=> $apps{$b}[MEMORY] +}@core2Apps; foreach my $application (@sortedAppsbyMemory) { print "$application @{$apps{$application}}\n"; } __END__ Prints: App4 4 PHP 2.8 2 App1 4 Perl 1.5 2 App5 8 C# 2.8 2 Note: App1 and App4 are equal in terms of CORES and MEMORY. Their order is unpredictable without further specification or considerations involving previous sorts. Above App4 sorts above App1. How to force App1 to be above App4 in all situations is an exercise left to the reader.
|
|---|