I have a input pipe delimiter file as:
IFB Northpole||| Alaska||| 907-555-5555
Walmart||| Fairbanks||| Alaska
Chicken||| Anchorage||| Alaska||| 907-555-5555
Beef||| Somewhere|||||Over the Rainbow|||907-555-5555
I want my output to be :
IFB Northpole| Alaska| 907-555-5555|
Walmart| Fairbanks| Alaska
Chicken| Anchorage| Alaska| 907-555-5555
Beef| Somewhere|Over the Rainbow|907-555-5555
Here is my code :
#!/usr/bin/perl
@FILES = glob("*.txt");
foreach my $file (@FILES) {
open my $fh, '<', $file;
(my $fileName = $file) =~ s/\.[^.]+$//;
open(my $output, '>', $fileName.".csv") or die "Could not open fil
+e '$fileName' $!";
my @category;
my @Detail;
print $output "";
while (my $line = <$fh>) {
chomp $line;
@tokens = split /\|/, $line;
chomp(@tokens);
$objectName=$tokens[0];
if($objectName ne ""){
my @objectFields;
$size = scalar(@tokens);
@tokens = @tokens[1..$size];
foreach my $token (@tokens){
$token =~ s/\r|\n//g;
push @objectFields,$token;
}
if($objectName eq "IFB Northpole"){
@Detail=@objectFields;
}elsif($objectName eq "Walmart"){
@category=@objectFields;
}elsif($objectName eq "Chicken"){
@category=@objectFields;
}elsif($objectName eq "Beef"){
my @item = (@Detail,@category,@objectFields);
print $output join("|", @item,@removeemptylines)."\n";
}
}
}
close $output;
close $fh;
}
How can i achieve this in perl? Any help would be appreciated.
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.