Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: Separating array contents

by space_monk (Chaplain)
on Jun 07, 2013 at 07:50 UTC ( #1037611=note: print w/ replies, xml ) Need Help??


in reply to Separating array contents

split will work, join all the array cells together into one string, then split on the ! characters

Update: some Monks have rained on my parade by noting that this may produce empty elements. :-) You can filter out empty elements with map or grep -(see below)

my $string = join( '', @mycells); my @result = split( '!', $string); # remove empty elements, using something like.... my @finalResult = grep { $_ ne '' }, @result;
If you spot any bugs in my solutions, it's because I've deliberately left them in as an exercise for the reader! :-)


Comment on Re: Separating array contents
Download Code
Replies are listed 'Best First'.
Re^2: Separating array contents
by choroba (Canon) on Jun 07, 2013 at 08:29 UTC
    Great. I thought of the same solution too, but I feared it would be too slow. I was not able to come with a faster one, though:
    #!/usr/bin/perl use warnings; use strict; use Test::More; use Benchmark qw(cmpthese); my @arr_s = qw/! my name ! is ! Achint ! I need ! help/; my @arr_ns = qw/ my name ! is ! Achint ! I need ! help/; sub simple { my @arr1 = split / *(!) */, join(' ', @_); shift @arr1 unless length $arr1[0]; return \@arr1; } sub complex { my @arr2; my $x = 0; my $step = 1; for (@_) { if ('!' eq $_) { $x += $step; push @arr2, '!'; } else { $arr2[$x] .= (defined $arr2[$x] ? ' ' : q()) . $_; } $step = 2; } return \@arr2; } print join ' # ', @{simple(@arr_s)}, "\n"; print join ' | ', @{simple(@arr_ns)}, "\n"; is_deeply([simple(@arr_s )], [complex(@arr_s )]); is_deeply([simple(@arr_ns)], [complex(@arr_ns)]); done_testing(); cmpthese(-5, { simple => sub { simple(@arr_s); simple(@arr_ns) }, complex => sub { complex(@arr_s); complex(@arr_ns) }, });

    Results on my netbook:

    Rate complex simple complex 10723/s -- -5% simple 11262/s 5% --
    لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

      Thank you for helping out

Re^2: Separating array contents
by MynameisAchint (Novice) on Jun 07, 2013 at 08:47 UTC

    Thank you for helping out

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1037611]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (7)
As of 2015-07-30 07:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (270 votes), past polls