Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl one-liner to convert first character uppercase - logic understanding

Tags:

regex

perl

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

like image 999
Ibrahim Quraish Avatar asked Jan 22 '26 01:01

Ibrahim Quraish


1 Answers

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.)

like image 192
devnull Avatar answered Jan 24 '26 22:01

devnull



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!