user8613163
user8613163

Reputation:

What does "$\=$/;" mean in perl?

I came across a perl program which counts the number of vowels in a string. But I'm not able to infer a single line how it is working. Anyone who can decode this program line by line?

$\=$/;map{
    $_=<>;print 0+s/[aeiou]//gi
}1..<>

Upvotes: 3

Views: 113

Answers (1)

ikegami
ikegami

Reputation: 386706

What does $\=$/; mean in perl?

Sets $\ to the value of $/.

$/ defines the line ending ending for readline (<>). It's default is a line feed (U+000A).

$\ is appended to the output of each print. It's default is the empty string.

So, assuming $/ hadn't been changed, it sets $\ to line feed, which makes print act like say.

Anyone who can decode this program line by line?

  1. Globally make print act like say.
  2. Read a line from ARGV.
  3. For a number of times equal to the number read,
    1. Read a line from ARGV.
    2. Use s/[aeiou]//gi to count the number of vowels.
    3. Print the result.

In scalar context, s///g returns the number of matches/replacements. 0+ forces scalar context.


By the way, tr/aeiouAEIOU// would be faster than 0+s/[aeiou]//gi, and no longer. It's also non-destructive.

Upvotes: 9

Related Questions