in reply to Regular Expression: search and replace
G'day sprkling,
Welcome to the monastery.
While there would be many ways to solve this, given a chapter title of "String and pattern match", choosing s///g sounds like you're right on target.
I see you subsequently replied with "I ended up just using an array ...". In essence, that also seems like a good move; however, without any code, it's impossible to know whether you've used that with a regular expression substitution or in some other way. The implementation of that idea might range from excellent to abysmal.
In general, a post along the lines of "I'm learning - here's an exercise - here's my solution - comments welcome", will get you constructive criticism on your code. If you can't find a solution, or what you do code produces warnings or errors, you can still post that but ensure you include the full text of the messages. Also, keep your code short, to the point and written in such a way that we can run it (and, where necessary, reproduce any problems you're encountering). Here's an example of what you might have posted for this specific question:
#!/usr/bin/env perl use strict; use warnings; my @number_names = qw{zero one two three four five six seven eight nin +e}; my $pattern = qr{ ( [0-9] ) }x; my @strings = ('8, 9, 5', '3-2-1-0', 'Testing: 1 2 3'); for my $string (@strings) { print "DIGITS: $string\n"; $string =~ s/$pattern/$number_names[$1]/g; print "NAMES: $string\n"; }
Output:
DIGITS: 8, 9, 5 NAMES: eight, nine, five DIGITS: 3-2-1-0 NAMES: three-two-one-zero DIGITS: Testing: 1 2 3 NAMES: Testing: one two three
"This is my first post on monks. please forgive me if I am not following exact posting rules."
Beyond the comments I've already made about not posting any code, this generally looks fine. Whenever you post, right below the textarea, you'll find useful tips and links to guidelines and further help. You can see these, at any time, by looking at the end of the Seekers of Perl Wisdom page.
-- Ken
|
|---|