i255d has asked for the wisdom of the Perl Monks concerning the following question:

I am new to Perl and working my way through one of the more popular Learning Perl Books. It usually takes me a while, but I can usually figure out why a certain piece of code in the Example sections works, but this time I am just not sure why. Here is the code:
#!/usr/bin/perl use strict; use warnings; use 5.010; die "No file names supplied!\n" unless @ARGV; my $oldest_name = shift @ARGV; my $oldest_age = -M $oldest_name; foreach (@ARGV) { my $age = -M; ($oldest_name, $oldest_age) = ($_, $age) if $age > $oldest_age; } printf "The oldest file was %s, and it was %.1f days old\n", $oldest_name, $oldest_age;
How does $age know to apply -M to the file going through the foreach loop?

Replies are listed 'Best First'.
Re: First Question, why something works? (-M)
by toolic (Bishop) on Apr 16, 2014 at 12:30 UTC

    -M uses $_. Tip #6 from the Basic debugging checklist ... B::Deparse

    sub BEGIN { use warnings; use strict 'refs'; require 5.01; } use warnings; use strict 'refs'; BEGIN { $^H{'feature_say'} = q(1); $^H{'feature_state'} = q(1); $^H{'feature_switch'} = q(1); } die "No file names supplied!\n" unless @ARGV; my $oldest_name = shift @ARGV; my $oldest_age = -M $oldest_name; foreach $_ (@ARGV) { my $age = -M $_; ($oldest_name, $oldest_age) = ($_, $age) if $age > $oldest_age; } printf "The oldest file was %s, and it was %.1f days old\n", $oldest_n +ame, $oldest_age;

    See also How do I compose an effective node title?

      So what you are saying is that when I use $age = -M; in my foreach loop, it is the same as me using $age = -M $_;?

        Hello i255d, and welcome to the Monastery!

        Yes, this is one of many places where Perl uses the special $_ variable implicitly, making it easier to write concise, elegant code. For a list of the places where Perl uses $_ implicitly, see the first entry in perlvar#General-Variables. (If you’re not already familiar with the Perl documentation site, bookmark it now and get to know your way around as soon as possible.)

        The Camel Book (4th Edition, p. 706) has this advice:

        Use the singular pronoun to increase readability:

        for (@lines) { $_ .= "\n"; }

        The $_ variable is Perl’s version of a pronoun, and it essentially means “it”. So the code above means “for each line, append a newline to it.”

        Hope that helps,

        Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

        Yes. If the argument is omitted, file test operators test $_ (except -t which tests STDIN).