Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: regex syntax and idomatic Perl

by AnomalousMonk (Archbishop)
on Mar 21, 2017 at 08:53 UTC ( [id://1185318]=note: print w/replies, xml ) Need Help??


in reply to regex syntax and idomatic Perl

The precedence problem has been covered. As for idiomaticity (?), how about:

c:\@Work\Perl>perl -wMstrict -le "for ('filesystem kbytes used avail capacity mounte +d on', '/dev/dsk/c0b0t0d0s4 12209400 5496486 6712914 46% /home' +, ) { printf qq{'%s' -> '%s' \n}, $_, parse_capacity($_); } ;; sub parse_capacity { my ($df_output) = @_; return $df_output =~ m[(\d+)%\s+/home$] ? $1 : 'Match Error'; } " 'filesystem kbytes used avail capacity mounted on' +-> 'Match Error' '/dev/dsk/c0b0t0d0s4 12209400 5496486 6712914 46% /home' -> '4 +6'

Update: Actually, if the structure of a data record really is that simple, it's not that much more effort to go ahead and parse the whole thing:

c:\@Work\Perl>perl -wMstrict -le "use Data::Dump qw(dd); ;; for ('filesystem kbytes used avail capacity mounte +d on', '/dev/dsk/c0b0t0d0s4 12209400 5496486 6712914 46% /home' +, ) { dd $_, parse_all($_); } ;; sub parse_all { my ($df_output) = @_; ;; my $match = my ($fsys, $kb, $used, $avail, $cap, $mtd) = $df_output =~ m{ \A (.+) \s+ (\d+) \s+ (\d+) \s+ (\d+) \s+ (\d+)% \s+ (.+) \z }xms; ;; return { error => 'Match Error' } unless $match; ;; return { fsys => $fsys, kb => $kb, used => $used, avail => $avail, cap => $cap, mounted_on => $mtd, }; } " ( "filesystem kbytes used avail capacity mounted on +", { error => "Match Error" }, ) ( "/dev/dsk/c0b0t0d0s4 12209400 5496486 6712914 46% /home", { avail => 6712914, cap => 46, fsys => "/dev/dsk/c0b0t0d0s4", kb => 12209400, mounted_on => "/home", used => 5496486, }, )


Give a man a fish:  <%-{-{-{-<

Replies are listed 'Best First'.
Re^2: regex syntax and idomatic Perl
by cbeckley (Curate) on Mar 21, 2017 at 14:02 UTC

    Ah, that's very cool:

    my $match = my ($fsys, $kb, $used, $avail, $cap, $mtd) = $df_output =~ m{\A (.+) \s+ (\d+) \s+ (\d+) \s+ (\d+) \s+ (\d+) % \s+ +(.+) \z}xms;

    I didn't know match could be used in a list context like that. Chaining the scalar assignment is a nice touch.
    Thank you.

    Thanks,
    cbeckley

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1185318]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2024-04-23 23:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found