http://www.perlmonks.org?node_id=1027683

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

Hi Monks

I have an array full of words. Some of them ending with ,|?|! etc. I want to remove/substitute these charcters so words like 'what?' just becomes 'what'.

I tried this-

foreach my $word (@array) { $word =~ s/(\.|\?|\!)$//; } foreach my $word (@array) { print "$word\n"; }

but sadly it does not work

Replies are listed 'Best First'.
Re: substitute within elements of array
by kcott (Archbishop) on Apr 09, 2013 at 10:18 UTC

    G'day Dr Manhattan,

    You say "... ending with ,|?|! ..." but your regex (s/(\.|\?|\!)$//) isn't removing commas. Is that the bit that isn't working? You really need to show your input and output: "it does not work" is an entirely inadequate error report.

    I think you'd be better off with a single character class ([?!,]) than an alternation with all those escaped characters:

    $ perl -Mstrict -Mwarnings -E ' my @words = ("what?", "what!", "what,"); say for map { s/[?!,]$//; $_ } @words; ' what what what

    -- Ken

Re: substitute within elements of array
by choroba (Cardinal) on Apr 09, 2013 at 09:24 UTC
    Works for me. What exactly is in the @array?
    #!/usr/bin/perl use warnings; use strict; my @array = qw/what what? what. what!/; foreach my $word (@array) { $word =~ s/(\.|\?|\!)$//; } foreach my $word (@array) { print "$word\n"; }

    Output:

    what what what what
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: substitute within elements of array
by Anonymous Monk on Apr 09, 2013 at 09:26 UTC

    but sadly it does not work

    Sure it does

    @array = qw[ SURE! IT! DOES! ]; foreach my $word (@array) { $word =~ s/(\.|\?|\!)$//; } die "@array"; __END__ SURE IT DOES at - line 6.

    What is the reason you didn't post your @array?