question: text substitution using Perl
Kevin D. Clark
kclark at elbrysnetworks.com
Mon Oct 23 14:06:46 EDT 2006
Zhao Peng writes:
> Thanks a lot for your help. I have 3 derived questions from your script.
No problem, glad to help.
> Question 1:
> For the back references, you used ${1} for the 1st captured buffer,
> while some books/people simply use $1, I'm wondering if you use {} as
> an extra caution to make sure it refers to the 1st captured buffer in
> case there are some digits followed.
No, I wrote it this way just to make the code clear -- there wasn't a
technical reason for this.
>
> Question 2:
> line 1> perl -i.bak \
> line 2> -pe 's/ \$(\d+)\. / \$ebcdic${1}. /g;
> line 3> s/ (\d+)\. / s370ff${1}. /g;' \
> line 4> your-directory-somewhere/*readme*
>
> On the end of line 1 and 3, you have a back slash. Is it for
> separating input to separated lines for better readability? If so, why
> is there no back slash on the end of line 2?
There is no backslash on line 2 because the shell knows that it is
reading a literal string and that the end of the string is marked by
the trailing single-quote (') character.
Just to be absolutely clear, this has nothing to do with Perl. This
notation has everything to do with the shell. If you're using Linux,
your shell might be something like bash or csh or zsh.
To see what is going on here you might try typing
echo hello there
echo hello \
there
echo 'hello\nthere'
echo "hello\nthere"
echo $PATH
echo "$PATH"
echo '$PATH'
...into your shell (especially the first two examples).
> Question 3:
> You used a period "." after ${1}, wouldn't it be safe to use "\." as
> the original string only ends with a period and we don't want to
> change it? I think "." can match any single character except a newline.
No...it wouldn't be safer to use "\." instead of "." in the
replacement part of the expression because the notation of "." only
has the semantics of "(generally) match any character except newline"
in the *match* part of the expression, *not* in the replacement part
of the expression.
Perhaps this example helps illustrate this?
echo "2a" | perl -pe 's/\d./hello./'
That last "." is interpreted fairly literally in this context.
Regards,
--kevin
--
GnuPG ID: B280F24E Never could stand that dog.
alumni.unh.edu!kdc -- Tom Waits
More information about the gnhlug-discuss
mailing list