Operating System - HP-UX
1748128 Members
4259 Online
108758 Solutions
New Discussion юеВ

perl - more concise way to split scalar string into 2-dimensional array ?

 
John Kittel
Trusted Contributor

perl - more concise way to split scalar string into 2-dimensional array ?

In the interest of improving my perl skills, is there a better way to write the following piece of code?

@lines = split /^/, $response->content();
foreach $line (@lines) {
($mtime, $filename) = split /" "/, $line;
@tmp = ($mtime,$filename);
push @APfiles,[@tmp];
}


response->content is returned from the LWP::UserAgent module; it is a scalar, string, containing a bunch of filenames and mtimes. The purpose of my code, above, is to convert the string to a 2 dimensional array, where each "row" is an mtime and a filename. It works the way I've written it, but I'm just wondering if there's a more perl-ish way of doing it.

- John

2 REPLIES 2
Hein van den Heuvel
Honored Contributor

Re: perl - more concise way to split scalar string into 2-dimensional array ?


Hmm,

Surely you can just drop the mtime and filename variables like:

@tmp=split /" "/, $line;

And if you have $_ 'free to use' then you can probably simply with

foreach $_ (@lines) {
@tmp = split;
:


Now can you also use:


foreach $_ (@lines) {
push @APfiles, split;
}


Hein.


John Kittel
Trusted Contributor

Re: perl - more concise way to split scalar string into 2-dimensional array ?

Thank you Hein.

The first suggestion worked, like this:

@lines = split /^/, $response->content();
foreach $line (@lines) {
@tmp=split /" "/, $line;
push @APfiles,[@tmp];
}

And the second worked, like this:

@lines = split /^/, $response->content();
foreach $_ (@lines) {
@tmp=split;
push @APfiles,[@tmp];
}

But the following isn't working for me yet, still puzzling over why...

@lines = split /^/, $response->content();
foreach $_ (@lines) {
push @APfiles,split;
}