http://www.perlmonks.org?node_id=963777

khacee has asked for the wisdom of the Perl Monks concerning the following question:

i have an input file containing: gs01.pri1.casino.sbo dns:192.168.101.21,icmp,http:302,https:200,tcp:80,tcp:443,wget

i want to split them like this: gso1.pri1.casino.sbo = $hostname dns:192.168.101.21 = $dns icmp = $icmp http:302 = $http https:200 = $https tcp:80 = $tcp1 tcp:443 = $tcp2 wget = $wget

Replies are listed 'Best First'.
Re: splitting array in filehandling
by GrandFather (Saint) on Apr 06, 2012 at 06:43 UTC

    What have you tried (show us some code) and how did it fail (show us what you got and what you expected)?

    You will find that using appropriate mark up, code tags in particular, will help us help you and thus encourage more monks to take an interest in your problem.

    True laziness is hard work
      Not to mention posting to the appropriate category :).

      I'm too lazy to be proud of being impatient.
Re: splitting array in filehandling
by brx (Pilgrim) on Apr 06, 2012 at 12:11 UTC
    fish vs fishing... :-/
    use strict; while (<DATA>) { my ($host,$proto) = split; my @proto = split /,/,$proto; my %c; for my $pr (@proto) { my ($p)= $pr =~ /(\w+)/; $c{$p}++; } my %num; print "$host = \$hostname"; for my $pr (@proto) { my ($p)= $pr =~ /(\w+)/; if ($c{$p} == 1) { print " $pr = \$$p"; } else { print " $pr = \$$p",++$num{$p}; } } print "\n"; } __DATA__ gs01.pri1.casino.sbo dns:192.168.101.21,icmp,http:302,https:200,tcp:80 +,tcp:443,wget gs02.pri1.casino.sbo dns:192.168.101.22,icmp,http:302,https:200,tcp:80 +,wget
    update: delete useless and overcomplicated code
Re: splitting array in filehandling
by Anonymous Monk on Apr 06, 2012 at 08:18 UTC

    use split, see Re: a perl, awstats and SHOUTCast history, csvpaste.pl, perlintro, Text::CSV/Text::xSV, site:perlmonks.org Text::CSV

    #!/usr/bin/perl -- use strict; use warnings; use Data::Dump qw/ dd /; open my($in),'<',\'gs01.pri1.casino.sbo dns:192.168.101.21,icmp,http:3 +02,https:200,tcp:80,tcp:443,wget'; while(<$in>){ #~ "\$hostname" => 'gso1.pri1.casino.sbo', #~ "\$dns" => 'dns:192.168.101.21', #~ "\$icmp" => 'icmp', #~ "\$http" => 'http:302', #~ "\$https" => 'https:200', #~ "\$tcp1" => 'tcp:80', #~ "\$tcp2" => 'tcp:443', #~ "\$wget" => 'wget' { my( $hostname, $rest ) = split ' ', $_, 2; my( $dns, $icmp, $http, $https, $tcp1, $tcp2, $wget ) = split +',', $rest; dd [ $hostname, $dns, $icmp, $http, $https, $tcp1, $tcp2, $wge +t ] ; } { my( $hostnamedns, $icmp, $http, $https, $tcp1, $tcp2, $wget ) + = split ',', $_; my( $hostname, $dns ) = split ' ', $hostnamedns, 2; dd [ $hostname, $dns, $icmp, $http, $https, $tcp1, $tcp2, $wge +t ] ; } } __END__ [ "gs01.pri1.casino.sbo", "dns:192.168.101.21", "icmp", "http:302", "https:200", "tcp:80", "tcp:443", "wget", ] [ "gs01.pri1.casino.sbo", "dns:192.168.101.21", "icmp", "http:302", "https:200", "tcp:80", "tcp:443", "wget", ]