Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: Removing chars from a word from an array

by murugu (Curate)
on Jan 24, 2006 at 15:22 UTC ( #525198=note: print w/ replies, xml ) Need Help??


in reply to Removing chars from a word from an array

Hi,

I dont know whether i understood your question correctly. If im not wrong what you need is to delete a set of characters from a word. But a character has to be removed only once in the word and has to be removed from @list.

use strict; use warnings; my @list= qw(a b c a c); my $w="kandabbbc"; while (my $a=shift(@list)) { $w=~s/\Q$a//; @list = grep {!/\Q$a/} @list; } print $w;

If you want to remove all the occurances of a character from the word, then

use strict; use warnings; my @list= qw(a b c a c); my $re = join '|', @list; my $w="kandabbbc"; $w=~s/$re//g; print $w;

Regards,
Murugesan Kandasamy
use perl for(;;);


Comment on Re: Removing chars from a word from an array
Select or Download Code
Re^2: Removing chars from a word from an array
by blazar (Canon) on Jan 24, 2006 at 16:20 UTC
    my @list= qw(a b c a c); my $w="kandabbbc"; while (my $a=shift(@list)) { $w=~s/\Q$a//; @list = grep {!/\Q$a/} @list; } print $w;

    OMG! while and grep to iterate over @list... ok, TMTOWTDI, but then how 'bout a for loop? Also, who told you that @list has duplicates? In any case, if so, then a technique a la'

    my %saw; for (@list) { next if $saw{$_}++; # ... }

    would suffice. Also, don't you think s///g would be better suited to remove chars from his string?

    Incidentally to remove charachters, the best tool would be tr///d a.k.a y///d, but unfortunately it does not interpolate - I don't know if it would be worth to use the usual eval trick to work around this limitation. The OP may still want to know just in case he really knew @list in advance and did not need to delete chars dinamically.

    my @list= qw(a b c a c); my $re = join '|', @list;

    How 'bout using a charachter class instead? That is:

    my $re=join "", @list; $re="[$re]";

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (9)
As of 2014-11-25 23:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (160 votes), past polls