Westcoast said:
Subject: newbie Perl question
Please put the subject of your post in the Subject of your post.
Be aware that the subject you have used will be read by mant people as
"Question I'm too lazy to figure out of myself. I'm too lazy to even
bother working out how what my question actually is".
Perl is looping through thousands of sentences. Each sentence begins and
ends with a quotation mark (")
In my script, these sentences are represented by "$data[2]"
What is the "perl command" to replace the LAST occurrence of each quotation
mark, with a period and a quotation mark?
What do you mean by "the LAST occurrence of each quotation mark"? Each
quotation mark can onlt appear once.
Example
"The day has come"
"He is happy"
...here's what I want:
"The day has come."
"He is happy."
Do you mean repace a quotation mark if it is the last character in the
string?
s/"$/."/;
Or do you mean replace the last quotation mark in the string?
s/"(?=[^"]*$)/."/;
or
s/(.*)"/$1."/;
I tried this:
$old = '\"';
$new = '\.\"';
Perhaps you should print out those strings and look what's in them.
You'll find there really are literal backslashes in there.
sub replace_word {
local($str, $old, $new) = @_;
In Perl one does not use local() to to introduce variables that are
local to a subrutine or block. One uses my(). For historical reasons
local() does something rather different (for details RTFM). Note this
will not actually prevent your code from working but unless you
understand what local() does you should not use it.
If you have a book or tutorial that shows local() being used in this way
it is hopelessly out of date (my() came in at 5.0 IIRC) and you should
discard it.
substr($str,rindex($str,$old),length($old)) = $new;
Perl has powerful regular expression based string manipulation tools.
Solutions based on substr/index/rindex can sometimes be a bit faster but
they are rarely as simple.
That said your solution should work if $old and $new contained the
correct values.
$str;
}
replace_word($data[2]);
You defined replace_word() as taking 3 arguments but only pass it one.
Within replace_word the variables $old and $new will therefore be undefined.
You defined replace_word() returning a modified copy of the string
(rather than changing the string passed to it in situ) but you don't do
anything with the return value.
Please see the posting guidelines. They contain much useful advice on
how you can help yourself and help others to help you.