Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Perl logic request for an IO scenario

by Athanasius (Archbishop)
on Apr 12, 2015 at 04:46 UTC ( [id://1123172]=note: print w/replies, xml ) Need Help??


in reply to perl logic request for an IO scenario

Hello Apronline,

In Perl, the usual way to handle this sort of lookup task is with a hash. As the hash data resides in memory, the hash should be populated with data from the smaller of the two files. In this case, it appears that File2 is the shorter, so you should begin by building a hash from File2 with key/value pairs of the form: 1 => 'Generic user error'.

Once you have this hash (i.e., lookup table), it is a straightforward task to go through the data in File1, line by line, extract the code element, and look it up in the hash using the exists function.

use strict; use warnings; my $file2 =<<EOF2; Code: description 1: Generic user error 2: Error with file location 3: File not found 4: Syntax error EOF2 my @desc = split m{\n+}, $file2; my %desc; for my $line (@desc[1 .. $#desc]) # Skip headings { chomp $line; my ($code, $desc) = $line =~ m{ ^ (\d+) : \s* (.+) $ }x; $desc{$code} = $desc; } <DATA>; # Skip headings while (my $line = <DATA>) { chomp $line; my @fields = split m{,\s*}, $line; if (exists $desc{$fields[1]}) { print join(', ', @fields, $desc{$fields[1]}), "\n"; } } __DATA__ Testname, code, date, file Test1, 4, 4/11/15, /tmp Test2, 2, 4/11/15, /log Test3, 1, 4/11/15, /log Test4, 7, 4/11/15, /dat Test5, 4, 4/11/15, /log

Output:

14:45 >perl 1214_SoPW.pl Test1, 4, 4/11/15, /tmp, Syntax error Test2, 2, 4/11/15, /log, Error with file location Test3, 1, 4/11/15, /log, Generic user error Test5, 4, 4/11/15, /log, Syntax error 14:45 >

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (5)
As of 2024-04-24 05:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found