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


in reply to regex help

Try this if you need to use regexp ;-) Following code will create two-dimensional array from your data. Header is skipped and line with dashes (delimiter between header and data) is used for regexp pattern creation.

#!/usr/bin/perl -w # use strict; use warnings; use Data::Dumper; my @data; my $data = 0; my $line; my @size; my $re; while ($line = <DATA>) { chomp $line; # remove EOL next if ($line =~ /^\s*$/); # skip empty lines if any if ($data) { # process data using regexp push @data, [ map { s/(^\s+|\s+$)//; $_ } ($line =~ /$ +re/) ]; } elsif ($line =~ /^-/) { # create regexp from pattern $data = 1; # end of header @size = map { length } split(/\s+/, $line); pop @size; $re = '^' . join(' ', map { "(.{$_})" } @size) . ' + (.*)'; } } print Data::Dumper::Dumper(\@data); __DATA__ Port Alias Oper Admin Speed Duplex Type (truncated) Status Status (bps) ------------ ---------------- -------- ------- ------ ------- -------- +---------- vlan.0.4094 up up other host.0.1 up up 10.0M other ge.1.1 down up 10.0M half 10-t + rj45 ge.1.2 down up 10.0M half 10-t + rj45 ge.1.3 down up 10.0M half 10-t + rj45 ge.1.4 down up 10.0M half 10-t + rj45 ge.1.5 down up 10.0M half 10-t + rj45