Hello, I'm attempting to parse this monster of a hosts file that is a most un-formatted file with ip4 and ip6 address with comments scattered everywhere. sometimes there are two columns separated by space, sometimes 3 columns, sometimes 4.

127.0.0.1 c2.gostats.com #SpySweeper.Spy.Cookie

127.0.0.1 ads.goyk.com

# 1-800-hostingAS3321069.41.160.0 - 69.41.191.255

127.0.0.1 2a02:598:2::1095

so i want to clean the old file by removing comments, and duplicates, so far i have
my @array = (); $#array = -1; my @tmp_array = (); $#tmp_array = -1; my @uniq = (); $#uniq = -1; my $i = 0; open(HOST_ORIG,'<', $file_read ) or die "Can't open $file_read: $!"; chomp(@array = <HOST_ORIG>); foreach $i (4...scalar(@array)-1) { (my $local_127, $tmp_array[$i] )=split(" ",$array[$i]); }; close(HOST_ORIG); my %seen; my @uniq = grep {! $seen{$_}++} sort(@tmp_array); open(TEMP, '>', $file_write)|| die "\n error opening file $file_write +\n"; print TEMP "#Hosts file\n"; print TEMP "#Last Modified -> ". localtime() . "\n"; print TEMP "# \n"; print TEMP "# localhost: Needs to stay like this to work\n"; print TEMP "127.0.0.1\t localhost\n"; print TEMP "# \n"; foreach $i (1...scalar(@uniq)-1) { print TEMP "127.0.0.1\t $uniq[$i]\n"; } close(TEMP);

it works except when there are 3 or more columns, the 3rd and 4rth columns get wrapped around to a new line like this

127.0.0.1 c2.gostats.com

#SpySweeper.Spy.Cookie

how do i throw away the rest of the line if it exists?

Thanks!


In reply to parsing a terrible /etc/hosts by f77coder

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.