Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Splitting output of a system command into an array

by lyklev (Pilgrim)
on Sep 30, 2007 at 21:51 UTC ( [id://641815]=note: print w/replies, xml ) Need Help??


in reply to Splitting output of a system command into an array

Let's use them all.

My free command shows the following lines:

total used free shared buffers cached Mem: 189656 180144 9512 0 6976 81012
(I show only the first two lines and output has been formatted for your screen)

First, use backticks to execute a command; it stores the output in an array, every line is an element. The output contains newlines, which are annoying. They can be stripped using chomp:

my @lines = `free`; # run command, store output chomp (@lines); # remove all newlines.

Next, we want to store the names of all fields of the second line by using split. The order is used later, so we use an array.

my @field_names = split (' ', $lines[0]); # split 1st line

The second line contains the memory numbers. We could use split to get the different elements, but to make it more interesting, we use regular expressions, marked by the =~:

my @mem_sizes = ( $lines[1] =~ m/(\d+)/g );

This line says: scan line 2 for matches of one or more digits (\d+). The parentheses around the digit remembers the found number. The 'g' repeats the process, and an array of found numbers is returned.

So now we have one array with numbers, and one array with the corresponding field names. Whenever you see 'corresponding' like this, you should think of a hash. Let's create one:

my %free; # a hash, where the fields will get stored

Now comes the magic:

@free { @field_names } = @mem_sizes;

Now, we can use the data by the field names instead of by their index, which will be easier to understand:

print("Cached: ", $free{'cached'}, "\n");

As an excercise left to the reader: in the line

@free { @field_names } = @mem_sizes;

why does it say @free, and not $free?

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (8)
As of 2024-04-23 22:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found