Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Arrary issues

by Cristoforo (Curate)
on Mar 25, 2019 at 21:24 UTC ( #1231670=note: print w/replies, xml ) Need Help??


in reply to Arrary issues

Hello deadlift

You were on the right road to consider using a hash.

Here is a possible solution using a hash (for the first shorter file).

#!/usr/bin/perl use strict; use warnings; my $File1 = <<EOF; Name, Job, City, State Jim, MD, Pinole, CA Tara, Nurse, San Pablo, CA Julie, MD, San Pablo, CA Sherry, Nurse, Pinole, CA George, MD, Pinole, CA Tim, Nurse, Pinole, CA Bob, Nurse, Pinole, CA Uma, MD, San Pablo, CA Kate, Nurse, Oakland, CA Pete, MD, San Pablo, CA EOF my $File2 = <<EOF; Name, Job, City, State Jim, Doctor, Pinole, CA Tara, Nurse, San Pablo, CA Julie, Doctor, San Pablo, CA Sherry, Nurse, Pinole, CA Jan, Doctor, San Pablo, CA George, Doctor, Pinole, CA Tim, Nurse, Richmond, CA Bob, Nurse, Pinole, CA Uma, Doctor, San Pablo, CA Kate, Nurse, Oakland, CA Paul, Doctor, Oakland, CA Ruth, Nurse, Richmond, CA Joe, Nurse, Oakland, CA Nick, Nurse, Pinole, CA Pete, Doctor, San Pablo, CA EOF my %occupation; open my $fh1, '<', \$File1 or die $!; <$fh1>; # throw away header line while (<$fh1>) { my ($name, $title) = split /, /; $occupation{$name} = $title; } close $fh1 or die $!; open my $fh2, '<', \$File2 or die $!; <$fh2>; # throw away header line while (<$fh2>) { my ($name, $title) = split /, /; if (exists $occupation{$name} and $occupation{$name} ne $title) { print $name, " => Prev: $occupation{$name}, Now: $title\n"; + } } close $fh2 or die $!;
You can see that I used strict and warnings which you should use (to identify errors or warnings in code).

That requires declaring the variables with my.

Also, it is good practice to check whether a file opening (or closing) occurred without error (the or die $! code on file openings and closings).

Although I didn't use Text::CSV here, it really should be used for more complex csv files.

Output:

C:\Old_Data\perlp>perl test2.pl Jim => Prev.: MD, now: Doctor Julie => Prev.: MD, now: Doctor George => Prev.: MD, now: Doctor Uma => Prev.: MD, now: Doctor Pete => Prev.: MD, now: Doctor

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (5)
As of 2020-09-28 23:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    If at first I donít succeed, I Ö










    Results (144 votes). Check out past polls.

    Notices?