CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Need a Custom or Prewritten Perl Program?: I need a program that...: Re: [liton79] Pattern search in txt file and output them with comma seperated value : Edit Log



Zhris
Enthusiast

Sep 18, 2013, 11:05 PM


Views: 11515
Re: [liton79] Pattern search in txt file and output them with comma seperated value

Hi,

This should work with your example input data:


Code
#!/usr/bin/perl 
use strict;
use warnings FATAL => qw( all );

#$/ = "\r\n";
$" = ", ";

my $filepath = 'input.txt';
my $key = undef;
my $hash = { };

# parse
open my $filehandle, '<', $filepath || die "cannot open $filepath: $!";
while ( <$filehandle> )
{
chomp;

if ( /^\s*(application|region|server)\s*$/i )
{
$key = lc $1;
}
elsif ( defined $key && /^\s*(.+)\s*$/ )
{
push @{$hash->{$key}}, $1;
}
}
close $filehandle;

# print
while ( my ( $key, $vals ) = each( %$hash ) )
{
print "$key, @$vals\n";
}



Code
region, NA  
application, ABC


Chris


(This post was edited by Zhris on Sep 18, 2013, 11:13 PM)


Edit Log:
Post edited by Zhris (Enthusiast) on Sep 18, 2013, 11:08 PM
Post edited by Zhris (Enthusiast) on Sep 18, 2013, 11:12 PM
Post edited by Zhris (Enthusiast) on Sep 18, 2013, 11:13 PM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives