目の前に僕らの道がある

勉強会とか、技術的にはまったことのメモ

ifconfigの出力をパースしてみる

こんな感じ?
正規表現がちょっとアレかなあ。

#!/usr/bin/env perl
use common::sense;

my @interfaces = split /\n\n/, `LANG=C; /sbin/ifconfig -a`;

my %reg = (
    link_encap  => qr/Link encap:(\S+)/,
    mac_address => qr/HWaddr\s(([[:xdigit:]]{2}:){5}[[:xdigit:]]{2})/,
    ip_address  => qr/inet addr:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/,
    netmask     => qr/Mask:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/,
    brordcast_address => qr/Bcast:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/,
);

my $data = {};
for my $interface (@interfaces) {

    if ($interface =~ /^(\S+)/) {
        my $ifname = $1;

        for my $attribute (keys %reg) {
            if ($interface =~ $reg{$attribute}) {
                $data->{$ifname}->{$attribute} = $1;
            }
        }
    }
}

use YAML;
warn YAML::Dump $data;