Dog, Table, 12:30, Mercury,abcdef
Dog, Chair, 5:30, Mercury,abcdef
Dog, Table, 12:30, Venus,abcdef
Pig, Door, 3:30, Earth, 123
Pig, Door, 3:30, Earth, 45678943985
Goat, Couch, 8:45, Mars, 9876
####
{Dog.txt}
Dog, Table, 12:30, Mercury,abcdef
Dog, Chair, 5:30, Mercury,abcdef
Dog, Table, 12:30, Venus,abcdef
{Pig.txt}
Pig, Door, 3:30, Earth, 123
Pig, Door, 3:30, Earth, 45678943985
{Goat.txt}
Goat, Couch, 8:45, Mars, 9876
####
#!/usr/bin/perl -w
use strict;
my $sourcefile = $ARGV[0];
my $currentline;
open(my $fh, '<', $sourcefile) or die ("Could not open $sourcefile");
#gets the filename from the cmd line
while(my $line = <$fh>) #until EOF, do the following
{
my $nextline =' ';
#initialize the next line to empty before starting
foreach my $line (<$fh>) #for every line go in
{
chomp($line);
my @currentline = split(/,/, $line); #split the fields
next if (($currentline[0]) eq (@nextline[0]));
#if 1st field in currentline = 1st field in the 2nd line
open OUT, ">> $currentline[0].txt" or
die "Could not open file $currentline[0].txt for output.\n$!";
#create the filename based upon the first field contents
#if the file already exists, append to it
print OUT $currentline;
#throw everything in that particular line into the file
$nextline = $currentline; #go to the next line
close OUT; #close the file
}
}