Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Help me understand this code?

by ansabhailte (Novice)
on May 21, 2015 at 20:27 UTC ( [id://1127399]=perlquestion: print w/replies, xml ) Need Help??

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

I'm very new to Perl (coming from Bash/sed/awk) and have been going through Daily Programmer challenges to get acquainted with Perl. I saw a user solution in Perl for a date sorter (yyyy-dd-mm, mm-dd-yyyy, etc reformatted) and am having a hard time figuring out what half of this means. Can anybody walk me through understanding it?
$m{$_} = ++$i for qw[Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec]; ($a, $t, $f, $b) = qw[([A-Za-z]+) \b(\d\d)\b (\d{4}) (\d{4}|\d\d)]; for (<>) { ($y, $m, $d) = /$f-$t-$t/ ? ($1, $2, $3) : /$t\/$t\/$t/ ? ($3, $1, $2) : /$t#$t#$t/ ? ($2, $1, $3) : /$t\*$t\*$f/ ? ($3, $2, $1) : /$a $t, $b/ ? ($3, $m{$1}, $2) : next; $y += $y < 50 ? 2000 : $y < 100 ? 1900 : 0; printf "%04d-%02d-%02d\n", $y, $m, $d; }

Replies are listed 'Best First'.
Re: Help me understand this code?
by aaron_baugher (Curate) on May 21, 2015 at 22:19 UTC

    I assume you're having trouble with the nested ternary operators. You could do the same thing with an if-elsif-elsif-else chain, but it wouldn't look as nice as this. This method lines up the tests and results nicely. Here's a very simple one to show what's happening:

    $result = $a ? $b : $c ? $d : $e ? $f : undef;

    So it starts left-to-right through the first ternary operator. It checks the value of $a; if that's true, it returns the value of $b, and the expression is finished. It doesn't continue on to the following ternary operators, since they're all part of the third section of the operator.

    But if $a is false, then it executes that third portion, which starts with the second ternary operator, checking the value of $c. If that's true, it returns the value of $d and stops. If $c is not true, it continues on to the third ternary operator, checking the value of $e, and so on.

    Adding some parens to make the precedence clearer, you'd have this:

    $result = $a ? $b : ( $c ? $d : ( $e ? $f : undef ));

    So in the case of your code, each of those ternary operator lines compares to a regex, and if it matches, it then returns the matching substrings $1, $2, and $3, as specified on the right, to $y, $m, and $d, and the statement exits, continuing with the $y+= line (which also has nested ternary operators working the same way). If none of them match, it eventually gets down to the next statement, restarting the loop because it couldn't recognize the string as having a date format.

    Aaron B.
    Available for small or large Perl jobs and *nix system administration; see my home node.

      Ah thank you!
Re: Help me understand this code?
by ww (Archbishop) on May 21, 2015 at 21:34 UTC

    Not the answer to your question (tho I will expand a bit on info sources), but the PRIMARY POINTS ILLUSTRATED BY THE CODE SHOWN ARE ... wait for them... just a little longer...

    1. Use meaningful variable names.
            $a and $b violate not only that wisdom, but should also be reserved for use in comparisons
            and...
    2. Don't get too lazy to type a few extra chars for clarity. Saving chars too enthusiastically will usually obfuscate your code rather than improve it.

    As to info sources: perldoc func, op, module_name is an incantation that will lead you to explanatory docs, right on your own computer. For example, for the regexen, you might want to see perldoc perlretut (or one of its siblings); for printf (which is a function and thus needs a "-f" before its name, thusly) perldoc -f printf (which will give you a referal to another function instead of usefully answer the question "what does it do?" unless you are intimate with sprintf's format arguement ...but that's a whole different can of worms); and, as an exercise to the OP, we have the likes of qw (for which vist re "quote word" and friends); some lists (defined by the square brackets) and a few more.

    ...and welcome to Perl and to the Monastery!

      SO I've been reading perlre and perlop and I get most of it now. But I'm still confused on the $m{$1} and $m{$_} parts. What do these do?

        %m is a hash mapping the 3 letter month to a month number.

        $m{$_} is where elements are being assigned inside a for loop.

        $m{$1} is dereferencing a particular value.

        -Greg
Re: Help me understand this code?
by GotToBTru (Prior) on May 21, 2015 at 20:40 UTC

    Run it in the debugger. You can inspect the variables and see what it is doing. This loops over standard input:

    for (<>) { ... }

    See perlop to understand what the operators are doing.

    Dum Spiro Spero
      https://gist.github.com/coderd00d/a88d4d2da014203898af This is the input. How do I feed it into it? (I know this sounds really noobish but the debugger pops up DB1 etc and I'm not sure what it's looking for exactly).
Re: Help me understand this code?
by Marshall (Canon) on May 22, 2015 at 06:52 UTC
    #!/usr/bin/perl; use warnings; use strict; # I am not sure what data set you have? # yyyy-mm-dd will sort in ASCII order # with a simple sort. # yyyy-dd-mm or mm-dd-yyyy is a bit more # complex, eg: 2013-11-07 vs 11-07-2013. # It is possible to detect yyyy-mm-dd # versus yyyy-dd-mm or mm-dd-yyyy, however # dd vs mm can be quite problematic. # 02-03-2011 vs 03-02-2011? # the code that you show is actually rather # strange looking. what are your trying to do? show some input and expected output.
      Yeah, that confused me too.

      It's a user-submitted solution to /r/dailyprogrammer.

      The input is:
      https://gist.github.com/coderd00d/a88d4d2da014203898af

      The output would be the same list in a standard format.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1127399]
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (3)
As of 2024-04-25 19:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found