You do
not need a hash. In fact, your original code is very close to doing what you want. Just a few tweaks:
#!/usr/bin/perl
use strict;
use warnings;
open(FILE2,">file1.txt")|| warn "Could not open\n";
open(FILE3,"file2.txt")|| warn "Could not open\n";
my $Previous = "";
my @data = <FILE3>;
my $index=0;
foreach my $_data (@data)
{
$index++;
chomp ($_data);
my @Current = split(/\s+/, $_data);
if ($index == 1)
{
# do nothing.
}
else
{
my @Previous = split(/\s+/, $Previous);
if ($Current[0] ne $Previous[0])
{
print FILE2 $Previous, "\n";
}
}
$Previous = $_data;
}
if ($Previous) {
print FILE2 $Previous, "\n";
}
close(FILE2);
close(FILE3);
I made the following changes:
- Added strict and warnings. Corrected @foo[0] to $foo[0] (see the perldiag entry for the warning it gave before), and declared variables.
- Moved the $index check so $Previous isn't used unless it's been set.
- Changed to split on whitespaces, not tabs (since the data you provided didn't have tabs).
- Add newlines to what's written out.
- Add block after the loop to print the final line that had been saved.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.