Parsing an array into rows and breaking it into more arrays

I still make Perl and know that I have a great way, I read Perl books from O'Reilly, also taught some Udemy lessons and even took Lynda's Perl course.

I'm trying to write a backup program to scratch the work I need, but it seems to be very hard for me 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'm only returning to one line, and I'm really not sure what I'm doing wrong, can someone point me in the right direction?

thanks

+4
source share
3 answers

Your problem is that you are 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 outside the loop now } 

Otherwise, you simply return after going through the cycle once, perhaps not what you want.

In addition, you must declare these arrays with my . Otherwise, Perl will complain about use strict , which you should always use.

Welcome to Perl!

Edit:

As Joel pointed out, you probably want to return references to these arrays. This is pretty easy to do, just use:

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

Refuse perlref if you are confused with this.

+5
source

You return after one iteration. Put the return out of the loop.

+3
source

Arrays can be really bulky and it looks a bit uncomfortable from here. This is a more idiomatic version that returns hashref of hashes stuffed with mount names (and assumes they are unique). I do not have zfs to check that this is unchecked, but it must be correct, and a call to Dumper should make it clear what is happening.

 use strict; use warnings; use Data::Dumper; $Data::Dumper::Terse = 1; print Dumper( list() ); sub list { my %info; for ( qx { zfs list } ) { my ( $name, $used, $available, $refer, $mount ) = split; $info{$name} = { used => $used, available => $available, refer => $refer, mount => $mount, }; } \%info; } 

If you're still going to use arrays, this syntax makes it a little less inconvenient to return -

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

Source: https://habr.com/ru/post/1441149/


All Articles