Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing an array line by line and exploding it into more arrays

I am still earning Perl , and know I have quite a way to go, I've been reading the Perl books from O'Reilly and also taking some classes on Udemy, and even went through the Lynda course on Perl.

I am trying to write a backup program to scratch a need I have, but I seem to be having a really hard time with one of my functions.

sub list {
    my @zfs_temp = `zfs list`;
    foreach (@zfs_temp) {
    my ($name, $used, $available, $refer, $mount) = split(/\s+/);
    push(@name, $name);
    push(@used, $used);
    push(@available, $available);
    push(@refer, $refer);
    push(@mount, $mount);
#    print "@name, @used, @available, @refer, @mount\n";
    return (@name, @used, @available, @refer, @mount);
    }
}

It seems that I am only getting back one line , and I'm really not sure what I am doing wrong, could anyone point me in the right direction?

Thank You

like image 762
Roncioiu Avatar asked Dec 27 '22 15:12

Roncioiu


2 Answers

Your problem here is that you're returning prematurely.

sub list {
    my @zfs_temp = `zfs list`;
    my (@name, @used, @available, @refer, @mount); #declared ahead of time and scoped appropriately 
    foreach (@zfs_temp) {
        my ($name, $used, $available, $refer, $mount) = split(/\s+/);
        push(@name, $name);
        push(@used, $used);
        push(@available, $available);
        push(@refer, $refer);
        push(@mount, $mount);
    }
    return (@name, @used, @available, @refer, @mount); #note how it's outside the loop now

 }

Otherwise you would simply return after going through your loop once, probably not what you want.

Additionally you should declare these arrays with a my. Otherwise Perl will complain under use strict which you should always use.

Welcome to Perl!

Edit:

As was pointed out by Joel, your probably want to return references to these arrays. It's pretty easy to do, just use:

return (\@name, \@used, \@available, \@refer, \@mount);

Check it out perlref if you're confused about that.

like image 103
Daniel Gratzer Avatar answered Dec 29 '22 03:12

Daniel Gratzer


You are returning after one iteration. Place return outside the loop.

like image 29
librarian Avatar answered Dec 29 '22 05:12

librarian