T
T
taaadm2015-02-10 12:59:14
Perl
taaadm, 2015-02-10 12:59:14

How is the list element obtained?

Here is the program from the Zabbix website :

#!/usr/bin/perl
 
$first = 1;
 
print "{\n";
print "\t\"data\":[\n\n";
 
for (`cat /proc/mounts`)
{
    ($fsname, $fstype) = m/\S+ (\S+) (\S+)/;
    $fsname =~ s!/!\\/!g;
 
    print "\t,\n" if not $first;
    $first = 0;
 
    print "\t{\n";
    print "\t\t\"{#FSNAME}\":\"$fsname\",\n";
    print "\t\t\"{#FSTYPE}\":\"$fstype\"\n";
    print "\t}\n";
}
 
print "\n\t]\n";
print "}\n";

Loop through the resulting list (`cat /proc/mounts`). But how does the list element get here? Where is there any assignment, for example? Explain, please

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
krypt3r, 2015-02-10
@krypt3r

Here is the assignment:
Shl. Solid shitcode. Better something like

#!/usr/bin/perl

use strict;
use warnings;
use JSON;
 
open my $F, '<', '/proc/mounts' or die "open() error: $!\n";
my ($fsname, $fstype, %result);
while (<$F>)
{
    ($fsname, $fstype) = (split /\s+/)[1, 2];
    #$fsname =~ s!/!\\/!g;
    push @{$result{'data'}}, {'{#FSNAME}' => $fsname, '{#FSTYPE}' => $fstype};
}
close $F;
print JSON->new->pretty->encode (\%result);

P
pcdesign, 2015-02-10
@pcdesign

This line is where the assignment occurs:
The $fsname variable is assigned $1, and the $fstype variable is assigned $2.
If you ask what is $1 and what is $2?
That is the result of what was found in the regular expression.
The first parentheses are $1.
The second parenthesis is $2.

D
dionys, 2015-02-19
@dionys

The operation ``returns a list of strings. In the loop for, each line implicitly goes into a special variable $_. The following operation m//also implicitly operates on this variable. Explicitly, the loop will look like this:

for my $_ (`cat /proc/mounts`) {
    ($fsname, $fstype) = $_ =~ m/\S+ (\S+) (\S+)/;
    ...
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question