Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

searching in array

by hotshot (Prior)
on Dec 10, 2001 at 21:39 UTC ( #130716=perlquestion: print w/replies, xml ) Need Help??

hotshot has asked for the wisdom of the Perl Monks concerning the following question:

I have an array of names, some of the names begin with '@', for example:
@arr = (test1, @test2, @test3, test4, test5)
does anyone have a short way to return from this array two strings?: one is the names without the '@' (separated by commas), and the second is the names with the '@', but after we cut the '@' from them.
for the above example I would expect:
$str1 = 'test1,test4,test5'; $str2 = 'test2,test3';
Thanks

Hotshot

Replies are listed 'Best First'.
Re: searching in array
by kwoff (Friar) on Dec 10, 2001 at 21:52 UTC
    I assume you meant
    @arr = qw(test1 @test2 @test3 test4 test5);
    In that case, you can use grep
    $str1 = join(',', grep {/^@/} @arr); $str2 = join(',', grep {/^[^@]/} @arr);
    Or you could use a foreach loop, push onto either of two arrays depending on the match, then join afterward.
Re: searching in array
by belg4mit (Prior) on Dec 10, 2001 at 21:47 UTC
    See grep.

    --
    perl -p -e "s/(?:\w);([st])/'\$1/mg"

Re: searching in array
by gbarr (Monk) on Dec 10, 2001 at 21:50 UTC
    @parts = map { tr/@//d; $_ } split /,?@/,join(",", reverse sort @arr), +2;

    Well you didn't ask for readable :)

Re: searching in array
by maverick (Curate) on Dec 10, 2001 at 21:47 UTC
    untested code:
    my @with; my @without; foreach (@arr) { if (/^\@(.*)/) { push(@with,$1); } else { push(@without,$_); } } my $str1 = join(",",@without); my $str2 = join(",",@with);
    straight forward and brute force...too early for me to think up a slick way to do it. ;)

    HTH

    /\/\averick
    perl -l -e "eval pack('h*','072796e6470272f2c5f2c5166756279636b672');"

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://130716]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (2)
As of 2023-02-04 08:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I prefer not to run the latest version of Perl because:







    Results (31 votes). Check out past polls.

    Notices?