Thi G. Thi G. - 25 days ago 7
Perl Question

Printing words with capital letters in Perl using regex

I tried to make an algorithm in Perl to print only words with only the first letter being a capital letter. For the example:

Hey
now
Brown cow


It should print:

Hey
Brown


But it is printing:

Hey
Brown cow


Here is my code:

while (<>) {
if (/^[A-Z][a-z]+/) {
print;
}
}

print "\n"

Answer Source

You're currently printing lines that begin with a capital word.

To print words, you'll need to adjust your regex to either capture words:

while (<>) {
    while (/\b([A-Z][a-z]+)/g) {
        print $1, "\n";
    }
}

Or separate words to begin with and then filter out the capital ones:

while (<>) {
    for (grep /^[A-Z]/, split) {
        print $_, "\n";
    }
}