http://www.perlmonks.org?node_id=1001158

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

I am reading a perl program, I have doubt in this line, pleas explain what the below lines do and why

if (/^$hash(server)/) { $uname = "not recognized"; }

Replies are listed 'Best First'.
Re: basic doubt
by Athanasius (Archbishop) on Oct 27, 2012 at 04:05 UTC

    Hello vis29, and welcome to the Monastery!

    The code shown applies the regex to whatever string is currently stored in the default variable $_, and if the regex matches it assigns the string "not recognized" to the scalar variable $uname.

    The regex says:

    • ^ — starting at the beginning of the string
    • $hash — match the current value of the scalar variable $hash
    • followed by the literal string 'server'
    • and capture the word 'server' if a match is found.

    I’m guessing that the code doesn’t do (anything like) what was intended, but without seeing the surrounding context it’s hard to say exactly what that was. Here is one guess:

    $uname = "not recognized" unless exists $hash{server};

    Hope that helps,

    Athanasius <°(((><contra mundum

Re: basic doubt
by AnomalousMonk (Archbishop) on Oct 27, 2012 at 17:29 UTC

    Athanasius has already clearly explained the OPed code as it stands.

    However, the use of the variable name  $hash followed by the capture of the literal string  'server' suggests either we are not seeing the real code or the real code is seriously bent. It is hard to imagine a case in which capturing a literally defined string has any point.

    A guess, given the variable name, is that the original intention was to deal with an actual hash element. Note the enclosing curly brackets rather than parentheses in this example, which I hope is self-explanatory:

    >perl -wMstrict -le "my %hash = (server => 'Foobar'); ;; $_ = 'Foobar today'; ;; my $uname; if (/^$hash{server}/) { $uname = 'not recognized'; } ;; print qq{$_ $uname}; " Foobar today not recognized
Re: basic doubt
by jdporter (Paladin) on Oct 27, 2012 at 18:22 UTC
Re: basic doubt
by aitap (Curate) on Oct 27, 2012 at 18:27 UTC

      That's a great utility if your regexes use no features introduced after Perl 5.6.x.


      Dave