Avoiding intermediate variables with chomp()

Answer

my %hash = ( key => grep [ chomp ], `which ps` );

John W. Krahn's original answer

Explaination

Normally you'd write it as

my %hash = ( key => grep chomp, `which ps` );

grep() runs through the list (in this case `which ps` that happens to only have one element) and applies the code given as first argument (chomp). If this code snippet returns a true value for a particular list element, this item is allowed to pass through.

The return value of chomp() is the number of characters removed from the end of the string so it returns true for any string it was able to shorten. Additionally, any changes done to $_ in the first argument to grep will show up in the returned list.

So grep filters and modifies its arguments in one go.

John used [ chomp ] instead of chomp. [ anything() ] will always have a true value when evaluated in boolean context. That way every element is passed on regardless.

Tassilo v. Parseval's orginal explaination of John's answer

Next