Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

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! :-)

Replies are listed 'Best First'.
Re^2: Separating array contents
by choroba (Chancellor) 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?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1037611]
[PriNet]: go figure, i just tried that, it retains some of the values (not the key) of the pre-assigned value
[PriNet]: i guess i'll just have to use two seperate hashes, there are two, but one is larger than the other, and when i reference the smaller one, it holds onto the values that were assigned to the larger hash (the keynames change, but unless i reassign a new valu

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (2)
As of 2017-06-28 02:56 GMT
Find Nodes?
    Voting Booth?
    How many monitors do you use while coding?

    Results (619 votes). Check out past polls.