Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Split an array of comma separated elements 2

Status
Not open for further replies.

BrianAtWork

Programmer
Apr 12, 2004
148
0
0
US
Hello,

I have an array of files:
Code:
my @array=('/tmp/file1,/tmp/files/file1','/tmp/file2,/tmp/files/file2');

Notice that there are 2 elements in @array, but each element is comma separated. I want a main array to contain all (in this example) 4 elements.
Currently, to accomplish this, I use a function, like this:
Code:
my @main_array=&split_array(@array);

sub split_array {
    my @files=@_;
    my @mainarray=();
    foreach my $fileline (@files){
        my @temp=split(/,/,$fileline);
        push (@mainarray,@temp);
    }#end foreach
    return @mainarray;
}

This works fine, but I was wondering if there was a better way to do this? I know you can't use something like @mainarray=split(/,/,@array), but are there other, better options?

Thanks in advance!

Brian
 
Code:
my @array=('/tmp/file1,/tmp/files/file1','/tmp/file2,/tmp/files/file2');
my @main = map { split /,/ } @array;
Seems to work.
 
Excellent. Yes, very nice answer - I was hoping the solution could be a simple one-liner.

I appreciate your help!
 
Okay, I'm going to resurrect this thread.
Expanding on knights' solution, how would I go about it if I wanted just the second half of the comma delimited string in each element of the array to be populated into the array?
So something like this:
Code:
my @array=('/tmp/file1,/tmp/files/file1','/tmp/file2,/tmp/files/file2');
#something happens here

#now @main contains /tmp/files/file1 and /tmp/files/file2

Is this possible? I know I can go through each element in @array, split on a comma, and push the 2nd one onto @main, but is there a more simplistic way?

Thanks again!
 
this should do it with the data set you posted:

Code:
my @array=('/tmp/file1,/tmp/files/file1','/tmp/file2,/tmp/files/file2');
my @main = map { (split(/,/))[1] } @array;
 
You are all wizards! Thank you so much! I need to learn how to use the map function a little better...

I really appreciate the help!

Thanks!

Brian
 
map is just a special loop, in and of itself it does nothing. It's the arguments or code used in the map block that does the work.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top