in reply to Identifying unmatched data in a database
Hello ardibehest, and welcome to the Monastery!
As LanX says, once you’ve opened a file you need to access it via the filehandle, not the filename. In addition, you should get into the habit of using the 3-argument form of open, using lexical variables instead of barewords for filehandles, calling close on the filehandle when the file is no longer being used, and always checking open and close for success or failure:
#!/usr/bin/perl use strict; use warnings; use constant { DATA_FILE => 'try.txt', MATCHED_FILE => 'matched.txt', UNMATCHED_FILE => 'unmatched.txt', }; open(my $input, '<', DATA_FILE) or die "Cannot open file '" . DATA_FILE . "' for reading: $!" +; open(my $matched, '>', MATCHED_FILE) or die "Cannot open file '" . MATCHED_FILE . "' for writing: $!" +; open(my $unmatched, '>', UNMATCHED_FILE) or die "Cannot open file '" . UNMATCHED_FILE . "' for writing: $!" +; while (my $line = <$input>) { chomp $line; my ($left, $right) = split /=/, $line; my @left_array = split / /, $left; my @right_array = split / /, $right; my $left_count = scalar @left_array; my $right_count = scalar @right_array; if ($left_count == $right_count) { print $matched "$line\n"; } else { my $diff = abs($left_count - $right_count); print $unmatched $line, "($diff) \n"; } } close $unmatched or die "Cannot close file '" . UNMATCHED_FILE . "': $ +!"; close $matched or die "Cannot close file '" . MATCHED_FILE . "': $ +!"; close $input or die "Cannot close file '" . DATA_FILE . "': $ +!";
Some notes:
It’s great that you use strict and warnings. Here are some additional pragmas you will find handy:
As you are new to Perl, be sure to check out chromatic’s book Modern Perl, which is available for free download at http://modernperlbooks.com/mt/index.html.
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Identifying unmatched data in a database
by AppleFritter (Vicar) on Jun 29, 2014 at 10:08 UTC | |
by hippo (Archbishop) on Jun 29, 2014 at 11:16 UTC | |
by soonix (Chancellor) on Jun 29, 2014 at 20:34 UTC | |
by Athanasius (Archbishop) on Jun 29, 2014 at 14:57 UTC | |
by Laurent_R (Canon) on Jun 29, 2014 at 15:24 UTC | |
|
Re^2: Identifying unmatched data in a database
by ardibehest (Novice) on Jun 29, 2014 at 11:07 UTC |