Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

Re: Simple Q. for You

by haukex (Bishop)
on Mar 16, 2018 at 08:46 UTC ( #1211016=note: print w/replies, xml ) Need Help??

in reply to Simple Q. for You

return 1 if ( $d->{foo} && $d->{foo} =~ /X/i )

Most of the following has already been covered by trippledubs, but let me lay it out in order:

  1. Something if Something is a statement modifier. That line of code is the same as

    if ( $d->{foo} && $d->{foo} =~ /X/i ) { return 1 }

    so let's look at it in that order. (Statement modifiers can make Perl read a lot more like English.)

  2. The first part of the if condition is $d->{foo}. ->{...} dereferences a hash reference (see perlreftut), in other words, $d is a reference to a hash, and we're asking Perl to look up the key foo in that hash.

  3. Since in the first part of the condition we're not applying any other operators other than &&, this means we are checking for whether $d->{foo} holds a true or a false value. Why would we want to do this? Most likely, because if $d->{foo} was undef, Perl would issue a warning later on when we use the =~ operator (more on that below). This also applies if the hash did not even contain a key foo - in this case Perl would also return undef for that key. (Note: You can check for undef explicitly with the defined function, and check for the existence of a hash key with exists. The fact that this code does not use these means that if $d->{foo} were to hold the value "0", then that would still be evaluated as "false". But since this code is looking for "X", that should not be a problem in this case.)

  4. The && operator "short-circuits", meaning that if the left side is false, the right side does not even get executed and tested, because if the left is false, we already know that the whole && will be false. If the left side is true, then the operator will test the right side.

  5. In the right side of the condition, $d->{foo} =~ /X/i, the =~ operator basically applies the regular expression /X/i to the string value of $d->{foo}.

  6. The regular expression (see perlretut) /X/i basically means "find X case-insensitively" - the /i is a "modifier" on the regular expression /X/ that turns on case-insensitive matching.

  7. The return statement will return the value 1 from the subroutine (or similar block) it is inside of, aborting its execution at that point (see also perlsub).

So taking all of that together, that line of code reads as "return 1 if the hash referenced by $d contains a key foo with a true value that also contains the string X (case-insensitively)".

Update 2019-08-17: Updated the link to "Truth and Falsehood".

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1211016]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (7)
As of 2021-01-19 19:15 GMT
Find Nodes?
    Voting Booth?