Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery

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';


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 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 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 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. ;)


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

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (7)
As of 2022-06-28 12:14 GMT
Find Nodes?
    Voting Booth?
    My most frequent journeys are powered by:

    Results (91 votes). Check out past polls.