in reply to Splitting output of a system command into an array
My free command shows the following lines:
(I show only the first two lines and output has been formatted for your screen)total used free shared buffers cached Mem: 189656 180144 9512 0 6976 81012
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?
|
|---|