use strict; use warnings; my @data = ( ['app12', 'eth1', 'static', '192.168.0.5', '255.255.255.0', '192.168.0.1'], ['app15', 'eth0', 'dhcp', '', '', ''], ['app15', 'eth1', 'static', '192.168.0.4', '255.255.255.0', '192.168.0.1'], ['app17', 'eth1', 'static', '192.168.0.2', '255.255.255.0', '192.168.0.1'], ); my %hosts; while (my @row = @{shift @data || []}) { push @{$hosts{$row[0]}}, \@row; } for my $host (keys %hosts) { genFile ($host, $hosts{$host}); } sub genFile { my ($host, $rows) = @_; my $fileName = "/tmp/interfaces.$host"; my @ifaces = map {$_->[1]} @$rows; print "--------- $fileName --------------\n"; print <## --------- /tmp/interfaces.app15 -------------- auto lo iface lo inet loopback auto eth0 eth1 iface eth0 inet dhcp iface eth1 inet static address 192.168.0.4 netmask 255.255.255.0 network 192.168.0.0 broadcast 192.168.0.255 gateway 192.168.0.1 --------- /tmp/interfaces.app12 -------------- auto lo iface lo inet loopback auto eth1 iface eth1 inet static address 192.168.0.5 netmask 255.255.255.0 network 192.168.0.0 broadcast 192.168.0.255 gateway 192.168.0.1 --------- /tmp/interfaces.app17 -------------- auto lo iface lo inet loopback auto eth1 iface eth1 inet static address 192.168.0.2 netmask 255.255.255.0 network 192.168.0.0 broadcast 192.168.0.255 gateway 192.168.0.1 #### my @hostRows; while ((my @row = @{shift @data || []}) || @hostRows) { if (@hostRows && (! @row || $row[0] ne $hostRows[0][0])) { genFile ($hostRows[0][0], \@hostRows); @hostRows = (); next if ! @row; } push @hostRows, \@row; }