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 TouchToneTommy 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 populated by a single value.

Status
Not open for further replies.

max1x

Programmer
Jan 12, 2005
366
US
If I wanted to split the array and get the value from it, is this the best way of doing this?

@array = qw (AA:BB:CC:DD:EE:FF);
@tmpArr = map {split":"} @array;
print $tmpArr[3];
 
Define best?

What you have works. This works too if @array doesn't really need to be an array (and I see no reason for it to be from what you posted).

my $array = qw (AA:BB:CC:DD:EE:FF);
my @tmpArr = split /:/, $array;
print $tmpArr[3];

[red]"... isn't sanity really just a one trick pony anyway?! I mean, all you get is one trick, rational thinking, but when you are good and crazy, oooh, oooh, oooh, the sky is the limit!" - The Tick[/red]
 
Some modules capture data in an @, so I don't have much control over that. I use shift or pop, since there is only one value in the output and assign a $var to it.

Creating a 2nd array vs shift or pop is that more efficent?
 
Probably best not to sweat over the efficiency unless you need to do it 10,000 times...

Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
this is the way to do it when @array has only one element:

Code:
@array = qw(AA:BB:CC:DD:EE:FF);
@tmpArr = split/:/,$array[0];
print $tmpArr[3];





------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
First of all: why use qw to define your array? You're only giving it one element. Seems to me that you only need a scalar.

Secondly, there's no need to create a temporary array for the output of split: just use a slice:
Code:
my $str = "AA:BB:CC:DD:EE:FF";

my ( $output ) = ( split /:/, $str )[3];

print "$output\n";
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top