Reputation: 4095
In the following Perl command lines, trying to turn the first and second char into uppercase
echo pet | perl -pe 's/^(.{0})(.)/$1\U$2/' # Ans: Pet
echo pet | perl -pe 's/^(.{1})(.)/$1\U$2/' # Ans: pEt
but could not understand the syntax (.{0})(.) and (.{1})(.)
Could you clarify how it works?
However, I found that the above can be simply achieved by the following syntax:
echo pet | perl -pe 's/(\w)/\U$1\E/' # Ans: Pet
echo pet | perl -pe 's/(\w)(\w)/$1\U$2/' # Ans: pEt
The back reference when placed between \U and \E will be converted to uppercase
Upvotes: 3
Views: 514
Reputation: 123478
The difference between:
echo pet | perl -pe 's/^(.{0})(.)/$1\U$2/' # Ans: Pet
echo pet | perl -pe 's/^(.{1})(.)/$1\U$2/' # Ans: pEt
is that nothing is matched in the first capture group in the first case, whereas p
is captured in the first group in the second case.
A shorter equivalent of the first case would be:
$ echo pet | perl -pe 's/^(.)/\U$1/'
Pet
Additionally, the following should clarify it:
$ echo pet | perl -pe 's/^(.{0})(.)/$1\U$2$2/'
PPet
(The second backreference is printed twice, and it produces 2 P
s.)
Upvotes: 2