Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

substitute within elements of array

by Dr Manhattan (Beadle)
on Apr 09, 2013 at 09:19 UTC ( #1027683=perlquestion: print w/ replies, xml ) Need Help??
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

Comment on substitute within elements of array
Download Code
Re: substitute within elements of array
by choroba (Abbot) 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?

Re: substitute within elements of array
by kcott (Abbot) 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

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1027683]
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (6)
As of 2014-09-23 03:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (210 votes), past polls