Can't create an array from the output of git pull

Viewed 59
use Cwd;
use strict;
use warnings;
no warnings 'numeric';


chdir("/root/dev/git_repo");

qx{git checkout master};
my $pull = qx{git pull};
if ($pull != "Already up-to-date."){
    my @output = $pull;
    chomp @output;
    foreach my $line (@output)
    {
        print "<<$line>>\n";
        }
    }

if ($pull == "Already up-to-date.") everything is fine, but

if ($pull != "Already up-to-date."){

then I won't be able to enter the loop, I'm not being able to convert the output to an array correctly. I tried other things like split /^/m, $pull.

I need to be able to parse it in order to get the files I need. I don't want to use any external libraries, because I have to use this script on old servers that are not connected to the internet.

1 Answers

This is a simplified version of your code:

use Cwd;
use strict;
use warnings;

chdir("/root/dev/git_repo");

qx{git checkout master};
my @lines = qx{git pull};
chomp @lines;

if ($lines[0] ne 'Already up-to-date.') {
    foreach my $line (@lines) {
        print "<<$line>>\n";
    }
}

You can directly populate an array using qx. This eliminates the need for multiple variables.


On my system, qx{git pull} returns Already up-to-date. with a newline character (\n) appended. Yours might as well. If so, your comparison would fail.

!= is only for numeric comparisons, but you are trying to do a string comparison. You would have gotten a warning message, but you intentionally suppressed that warning using this line:

no warnings 'numeric';

The warning tells you that your comparison will not behave as expected. Since this is the major source of your problem, don't suppress that warning. Perl warnings almost always mean you have a bug in your code.

Another issue with your code is this line:

my @output = $pull;

It populates the array variable with a single item. It does not magically split the git output into several lines by \n.

Related