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
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 Ps.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With