Perl: the Markov chain saw PerlMonks

### another elegance contest

by tos (Deacon)
 on Nov 16, 2005 at 12:24 UTC Need Help??

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

Hi folks,

so you don't think i'm deceased here a sign of life.

The problem is to pick some decided elements out of an array and put them into another.

My own solution works, but as far as i know perl, there must be a more elegant way to do this.

```# perl -we '\$i=0;\$x="klops";@a=(qw|apfel klops klops börne joghurt klo
+ps nüß|);for (\$i=\$#a;\$i>=0;\$i--) {print "\$i:",\$a[\$i],"\n";\$a[\$i]=~/\$x
+/ && push @e, (splice @a, \$i, 1)};print "@e\n@a\n"'
6:nüß
5:klops
4:joghurt
3:börne
2:klops
1:klops
0:apfel
klops klops klops
apfel börne joghurt nüß
Suggestions ?

regards, Thomas

Is simplicity best or simply the easiest Martin L. Gore

Replies are listed 'Best First'.
Re: another elegance contest
by salva (Canon) on Nov 16, 2005 at 13:00 UTC
```my \$x = qr(klops);
my @a = qw(apfel klops klops börne joghurt klops nüß)
my @e;
@a = grep { \$_ !~  \$x or not push @e,  \$_ } @a;
Salve SALVA, :-)

that's a really fabulous solution. It's just the kind of consise perl-semantics i like so much. Unfortunatly i'm only rarly able to create such pretty code-jewels by myself.

I also tried approaches with 'grep' but the 'not'-trick would never have occurred to me.

Thank you brother, ;-)

regards, tos

Is simplicity best or simply the easiest Martin L. Gore
Re: another elegance contest
by Eimi Metamorphoumai (Deacon) on Nov 16, 2005 at 15:37 UTC
```my \$x = "klops";
my @orig = qw(apfel klops klops börne joghurt klops nüß);

my (@have, @havenot);

push @{(/\$x/ ? \@have : \@havenot)}, \$_ for @orig;

print "@have\n@havenot\n";
If you want, you can assign @have back to @orig at the end.
Re: another elegance contest
by l.frankline (Hermit) on Nov 16, 2005 at 12:40 UTC

Hi,

Its my idea....

\$i=0;
\$x="klops";
@a=qw(apfel klops klops börne joghurt klops nüß);
@new = ();
for (\$i=0;\$i<=\$#a;\$i++)
{
if (grep/\$x/,\$a[\$i])
{
push (@new,\$a[\$i]);
delete (\$a[\$i]);
}
}

print @a;
print @new;

Thanx
Franklin
Don't put off till tomorrow, what you can do today.

Create A New User
Node Status?
node history
Node Type: perlquestion [id://508997]
Approved by jfroebe
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (3)
As of 2021-01-25 02:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
The STEM quote I most wish I'd made is:

Results (263 votes). Check out past polls.

Notices?