Reading data from file into an array to manipulate within Perl script

perl read file into array
perl read file line by line into array
perl read file into array split
perl read file into string
perl read file into variable
how to read multiple files from a directory in perl
perl script to print lines from a file
perl split lines into array

New to Perl. I need to figure out how to read from a file, separated by (:), into an array. Then I can manipulate the data.

Here is a sample of the file 'serverFile.txt' (Just threw in random #'s) The fields are Name : CPU Utilization: avgMemory Usage : disk free


I would like to figure out how to get each field into its appropriate array to then perform functions on. For instance, find the server with the least amount of free disk space.

The way I have it set up now, I do not think will work. So how do I put each element in each line into an array?


use warnings;
use diagnostics;
use v5.26.1;

#Opens serverFile.txt or reports and error
open (my $fh, "<", "/root//Perl/serverFile.txt") 
    or die "System cannot find the file specified. $!";

#Prints out the details of the file format
sub header(){
    print "Server ** CPU Util% ** Avg Mem Usage ** Free Disk\n";
    print "-------------------------------------------------\n";

# Creates our variables
my ($name, $cpuUtil, $avgMemUsage, $diskFree);
my $count = 0;
my $totalMem = 0;

# Loops through the program looking to see if CPU Utilization is greater than 90%
# If it is, it will print out the Server details
while(<$fh>) {
    # Puts the file contents into the variables
    ($name, $cpuUtil, $avgMemUsage, $diskFree) = split(":", $_);
    print "$name **  $cpuUtil% ** $avgMemUsage% ** $diskFree% ", "\n\n", if $cpuUtil > 90;
    $totalMem = $avgMemUsage + $totalMem;
print "The average memory usage for all servers is: ", $totalMem / $count. "%\n";

# Closes the file
close $fh;

For this use case, a hash is much better than an array.

use strict;
use feature qw{ say };
use warnings;

use List::Util qw{ min };

my %server;
while (<>) {
    my ($name, $cpu_utilization, $avg_memory, $disk_free)
        = split /:/;
    @{ $server{$name} }{qw{ cpu_utilization avg_memory disk_free }}
        = ($cpu_utilization, $avg_memory, $disk_free);

my $least_disk = min(map $server{$_}{disk_free}, keys %server);
say for grep $server{$_}{disk_free} == $least_disk, keys %server;

Reading from a file in scalar and list context, In this case, after opening the file we read from the $fh filehandle into an array variable: my @rows = <$fh>;. In this case Perl will read in the content of the whole​  A Perl “read file into array” example. If you want to read a complete text file into a Perl array, you only need one line of code, like this: @lines = <>; Assuming your program is named, and you want to read a file named gettysburg-address.txt, all you need to do to read that file from your program is to run your program like this:

Open and read from text files, Unique values in an array in Perl · Manipulating Perl arrays: shift, unshift, In this part of the Perl tutorial we are going to see how to read from a file in Perl. First, using a text editor, create a file called 'data.txt' and add a few lines to it: files is used in Perl scripts when you absolutely have to have the file opened or there  The file handle is then used with Perl's input operator <> to read the contents of the file into the @data array. Each element of the array now corresponds to one line of the file.

To your original question about how to store the data in an array...

First, initialize an empty array outside the file read loop:

my @servers = ();

Then, within the loop, after you have your data pieces parsed out, you can store them in your array as sub-arrays (the resulting data structure is a two dimensional array):

$servers[$count] = [ $name, $cpuUtil, $avgMemUsage, $diskFree ];

Note, the square brackets on the right create the sub-array for the server's data pieces and return a reference to this new array. Also, on the left side we just use the current value of $count as an index within the @servers array and as the value increases, the size of the @servers array will grow automatically (this is called autovivification of new elements). Alternatively, you can push new elements onto the @servers array inside the loop, like this:

push @servers, [ $name, $cpuUtil, $avgMemUsage, $diskFree ];

This way, you explicitly ask for a new element to be added to the array and the square brackets still do the same creation of the sub-array.

In any case, the end result is that after you are finished with the file read loop, you now have a 2D array where you can access the first server and its disk free field (the 4-th field at index 3) like this:

my $df = $servers[0][3];

Or inspect all the servers in a loop to find the minimum disk free:

my $min_s = 0;
for ( my $s = 0; $s < @servers; $s++ ) {
    $min_s = $s  if ( $servers[$s][3] < $servers[$min_s][3] );
print "Server $min_s has least disk free: $servers[$min_s][3]\n";

Like @choroba suggested, you can store the server data pieces/fields in hashes, so that your code will be more readable. You can still store your list of servers in an array but the second dimension can be hash:

$servers[$count] = {
    name          => $name,
    cpu_util      => $cpuUtil,
    avg_mem_usage => $avgMemUsage,
    disk_free     => $diskFree

So, your resulting structure will be an array of hashes. Here, the curly braces on the right create a new hash and return the reference to it. So, you can later refer to:

my $df = $servers[0]{disk_free};

Kan-Ju Lin: [Perl] Read file and store data in arrays, While bash script might be handy to use, it can only do integer arithmetic. I have two columns of data, in which I want to manipulate the values in  In this case, after opening the file we read from the $fh filehandle into an array variable: my @rows = $fh>;. In this case Perl will read in the content of the whole file in one step. Each row in the file will be one of the elements of the array. So if the file had 37 rows, then this array will have 37 elements.

Perl 'split' function, Perl FAQ: How can I split a string in Perl, such as the strings in a pipe-delimited Many times you need a Perl script that can open a plain text file, and I'll read all of the fields in each record into an array named @fields , and  Instead of starting with the json file and reading it into my Perl program, I’d like to define this data structure in my program and then call encode_json to create the json file. I’m fairly new to Perl hashes and arrays. “Boss” is a hash and “employees” is an array of hashes. I need to incorporate both of these into one data structure.

Parsing Text Files With Perl, Learn how to parse simple tab separated text files with Perl. See an What it does first is open a file called data.txt (that should reside in the same directory as the Perl script). Using Foreach to Loop Through an Array in Perl. You “open” files in Perl using the open function. When you open a data file, all you have to do is specify (a) a file handle and (b) the name of the file you want to read from. For example, suppose you need to read some data from a file named checkbook.txt. Here’s a simple open statement that opens the checkbook file for read access:

Reading | Working with Files in Perl, Begin to incorporate files into your Perl programs by learning how to open, This topic will be covered in Hour 12, "Using Perl's Command-Line Tools." Remember that every line of data read in with a filehandle in Perl contains manipulate the array elements, and deal with the array's contents with all  In this first “Perl split” example program, I’ll read all of the fields in each record into an array named @fields, and then I’ll show how to print out the first field from each row. This example shows several things, including how to split a record by the : character, which is the column delimiter in the Linux /etc/passwd file.