StayCalm
StayCalm

Reputation: 145

Parsing hash in perl to CSV format

I need to parse my text file (my output) to csv format, which contains just Names and Ips from devices. Somthing like:

Name, ip
LAB-W, 10.66.1.12
LAB-D, 10.66.1.13

I do not have experience with parsing in perl, maybe somebody can help me with this question.

use Net::Cisco::ISE;
use Data::Dumper;
use Text::CSV;

my $ise = Net::Cisco::ISE->new(hostname=>'hostname', username=>'user', password=>'user');

for my $name (keys %{$networkdevices}){
    my $device = $ise->networkdevices("id" => $networkdevices->{$name}->id);
    print Dumper $device->name;
    print Dumper $device->NetworkDeviceIPList;
}

And I have this output:

$VAR1 = 'LAB-W';
$VAR1 = {
     'NetworkDeviceIP' => {
         'mask' => '32',
         'ipaddress' => '10.66.1.12'
      }
};
$VAR1 = 'LAB-D';
$VAR1 = {
     'NetworkDeviceIP' => {
          'mask' => '24',
          'ipaddress' => '10.66.1.13'
      }
};

I tried this script (from this post), but I do not see output, also no mistakes :

use DBI;
use strict;
use Data::Dumper;
use File::Slurp;

open (FILE, "<./my_output") or die "could not open file: $!";
undef $/;

my $contents = <FILE>;
close(FILE);

my $hash_of_arrays = eval $contents;

for my $key (keys %$hash_of_arrays) {
    my $hash = $hash_of_arrays->{$key};
    for my $key2 (keys %$hash) {
        my $array = $hash->{$key2};
        for my $i (0..$#$array) {
            print "$i: $$array[$i]\n";
        }
    }
}

Upvotes: 2

Views: 187

Answers (1)

xxfelixxx
xxfelixxx

Reputation: 6602

Since the data are just in a hash, you can access them directly inside your loop:

for my $name (keys %{$networkdevices}){
    my $device = $ise->networkdevices("id" => $networkdevices->{$name}->id);
    print join(',',
       $device->name
       $device->NetworkDeviceIPList->{NetworkDeviceIP}->{ipaddress}
    ) . "\n";
}

Upvotes: 2

Related Questions