Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

basic doubt

by vis29 (Initiate)
on Oct 27, 2012 at 03:50 UTC ( #1001158=perlquestion: print w/replies, xml ) Need Help??
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 (Chancellor) 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 (Chancellor) 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 (Canon) 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.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1001158]
Approved by Athanasius
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (6)
As of 2018-06-18 15:58 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (110 votes). Check out past polls.