in reply to Re: grep unique values , remove the blank spaces and store it in a variable
in thread grep unique values , remove the blank spaces and store it in a variable

Thanks for the reply, I tried that method and it works the same way as it is now. The unique values are getting captured but there are a bunch of empty lines
push(my @array, $lanip) if ! $seen{$lanip}++; #print "@array\n"; my %hash = map { $_, 1 } @array; my @unique = keys %hash; print "@unique\n";
output
192.169.30.0 192.169.31.0 192.169.32.0 192.169.72.0
How can I remove them?

Replies are listed 'Best First'.
Re^3: grep unique values , remove the blank spaces and store it in a variable
by poj (Abbot) on Sep 14, 2015 at 07:44 UTC

    add another condition to the if/unless

    #!/usr/bin/perl use strict; use XML::Simple; my $xml = do {local $/='';<DATA>} ; my $servers = XMLin($xml); my %seen=(); my @array=(); foreach my $server (@{$servers->{server}}) { my $lanip = $server->{LanIP}; $lanip =~s/\d+$/0/; push(@array, $lanip) unless ( $seen{$lanip}++ || $lanip eq ''); } print join "\n",@array; __DATA__ <xml> <server LanIP="192.169.30.123"/> <server LanIP=""/> <server LanIP="192.169.30.24"/> <server LanIP=""/> <server LanIP="192.169.31.126"/> <server LanIP="192.169.32.127"/> </xml>
    poj

      The substitution of 0 is indeed mysterious, and indeed substr would not help for 192.169.30.24.

      Probably the programmer would like to split network number from host part for IPv4 addresses. Dotted quad notation is for the readers convenience, manipulation is better done in binary. Replacing the last quad only works for a mask of 255.255.255.0 and 192.169.30.214/28 would not be split properly.
      The following strips off the host part, but would not work for IP v6
      use Socket; ... my $addr = $server->{LanIP}; my $mask = my $mask = $server->{Netmask}; my $netaddr = inet_ntoa(inet_aton($mask) & inet_aton($addr)); push(@array, $netaddr) unless $seen{$netaddr}++;
Re^3: grep unique values , remove the blank spaces and store it in a variable
by Discipulus (Canon) on Sep 14, 2015 at 07:56 UTC
    Hello if you want to filter out, let's say, keys that does not starts whit number, you can change
    my %hash = map { $_, 1 } @array;
    with
    my %hash = map { $_, 1 } grep {$_=~/^\d/} @array;

    Anyway if i understand it must be only one key like this. maybe better you use Data::Dump's dd to inspect the array.

    Also some garbage can come from (deprecated) XML::Simple. Try to switch to something usable like XML::Twig.

    UPDATE: obviously the sage Athanasius is right here below, code does not make much sense: but i cant find where the foreach loop ends, too. Also the substr($lanip, 11, 3) = "0"; part seems very erro prone, maybe something like  s/\d{1,3}$/0/ is better (if i understand the will of OP)
    HtH
    L*
    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.