Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Beautiful code I wrote ;-)

by Skeeve (Parson)
on Jul 10, 2008 at 22:23 UTC ( [id://696839]=perlmeditation: print w/replies, xml ) Need Help??

Some people say, perl code looks ugly.

I always object!

And just an hour ago I wrote something that looked really beautiful to me ;-) and I like to share it with you.

My piece of code has a number from 0 to 9 in $_ and should set the corresponding bit (count starts from 1 here so 1 is bit zero). If the number is zero, the result should be Zero.

Being a mathematician by heart ;-) I first wrote 2**$_/2, but that gives me 0.5 for $_ being 0. I didn't want to use int().

Then I remembered >> and wrote: 2**$_>>1 and suddenly realised! 2** is the same as 1<< and So I came to:

1<<$_>>1

Don't you agree that this is a perfect looking little piece of code? ;-)


s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
+.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e

Replies are listed 'Best First'.
Re: Beautiful code I wrote ;-)
by moritz (Cardinal) on Jul 10, 2008 at 22:30 UTC
    It's beautiful.

    And unreadable. If you didn't write it, I'd had no idea what it meant. To decode it you first have to remember that << and >> are bit shift operators (not a big deal), but then you have know their relative precedence, and if they are equal, even their associativity.

    If you remember that 2 ** $_ / 2 == 2 ** ($_ -1), you can write it with just one bit shift operation.

      Exactly. I think that sort of stuff is fine for your own little personal projects (I to enjoy everytime I discover a more obfuscated way of doing something) , but in the workplace or for Opensource projects it is one of the reasons a lot of people dislike Perl, and fair enough as well.
Re: Beautiful code I wrote ;-)
by martin (Friar) on Jul 11, 2008 at 06:17 UTC
    Ah, Sudoku meets Perl golf. :-)

      ++ for the right guess!

      I'm writing a Palm modul for accessing sudokus stored in Andrew Gregory's great Sudoku program.


      s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
      +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e
Re: Beautiful code I wrote ;-)
by eyepopslikeamosquito (Archbishop) on Jul 11, 2008 at 13:01 UTC

    This reminds me of the pleasingly symmetrical expression from the Shiny Ball Book (aka Effective Perl Programming) for finding the minimum of two numbers:

    [ $a => $b ] -> [ $b <= $a ]

Re: Beautiful code I wrote ;-)
by ysth (Canon) on Jul 11, 2008 at 04:24 UTC
    I first wrote 2**$_/2, but that gives me 0.5 for $_ being 0. I didn't want to use int().
    You can avoid the int() by making it implicit:
    $ perl -wle'print [0..256]->[2**$_/2] for 0..9' 0 1 2 4 8 16 32 64 128 256
Re: Beautiful code I wrote ;-)
by ack (Deacon) on Jul 11, 2008 at 16:44 UTC

    It *is* beautiful! Symmetry seems to be a powerful attractant visually; I am always fascinated by it. Nice job!

    Spending most of my time applying Perl to my real-world problems sledom leaves me much opportunity to appreciate some of the eye-pleasing constructs, obfuscated Perl or not, that pop up. I would, of course, agree with moritz and kalium that I wouldn't want your construct in my work code...nightmare to try to maintain...especially by someone other them myself if I put it there. But I'm presuming you would already know that and just found the construct beautiful.

    Thanks for giving me a moment to just "stop and smell the roses" (so to speak) and see code through different glasses.

    ack Albuquerque, NM

      To be honest: It's still in there.

      I don't see why this code should be "obfuscation". Yes. It might be difficult to tell the precedence of << and >> (which is equal) or the associativity. But that's the same with any operator.

      Just because it's seldom used doesn't make this a valid argument.

      And I think bitshifting is more appropriate to the task at hand than multiplication. After all: I have to set one bit.

      The only way I can think of making it clearer is either (1<<$_)>>1 or 1<<($_-1) The later I think is a bit unclear as one has to know that shifting left by a negative amount is in fact shifting right.


      s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
      +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e

        You know, I've thought about this post for several days and I think it is not nearly as 'obfuscated' as I had originally thought.

        The shift operator is one we actually us a lot in our work and I got to thinking and wandering how much we used it. That thinking got me curious and I looked back at various test modules we've written to see just how often it does show up (I even wrote a little Perl script to go through our current stock of modules and actually count how many times it shows up...my associates now think I'm totally crazy). It shows up even more than I had remembered.

        More importantly, I actually found your very constuct in one of our modules. It had a bunch of parentheses around to try to 'make it clearer'...it actually now looks much more obfuscated that your more eye-pleasing construct.

        Out of curiosity about how my more seasoned test module programmers would see your construct, I showed a couple of them your construct and the one in our code (neither of them was the author of our version). Both of them said (I paraphrase) "Wow! Much cleaner!"

        So I would have to back off from thinking yours was 'obfuscated.' Depending upon one's perspective and needs I can see how one might say your construct could be perceived as 'obfuscated' (certainly I did at first); I wouldn't begin to argue...I'm not that experienced. But I, for one, have revised my opinion in those terms.

        But independent of whether one sees your beautiful construct that you put forth, it still remains very beautiful to me.

        ack Albuquerque, NM
Re: Beautiful code I wrote ;-)
by roboticus (Chancellor) on Jul 10, 2008 at 23:13 UTC
Re: Beautiful code I wrote ;-)
by ambrus (Abbot) on Jul 15, 2008 at 12:53 UTC

    Doesn't C have an obligatory warning for this?

      NO.
      even with -Wall -pedantic, gcc does not complain. And there would be no reason to. 1 << a >> 1 is very much a well-formed C expresion, meaning "shift left the int with value '1' by 'a' bits; shift right the result by one bit".
      []s, HTH, Massa

        Gcc indeed doesn't seem to complain, however, there was a reason why I remembered there was a warning, and it's a different compiler. Borland C 3.1 has such a warning.

        Update: I recreated a variant of the screenshot I've linked to and made a text export. Non-ascii characters are wrong so the image I linked to is still better, but I copy the text version here in case you can't view the image and because it's not hosted on perlmonks.

        = File Edit Search Run Compile Debug Project Options Wind +ow Help +--------------------------------- \TEMP\A.C ------------------------- +---2-----+ |#include <stdio.h> + | |int +-[_]---------- About ----- +---------+ |main(void) { | + | | return(1 << 5 >> 1); | Borland C++ + | |} | + | | | Version 3.1 + | | | + | | | Copyright (c) 1990, 19 +92 by | | | + | | | Borland International, + Inc. | | | + | | | OK _ + | | | ________ + | | +-------------------------- +---------+ +------- 4:21 -------------------------------------------------------- +---------+ +-[_]------------------------------ Message -------------------------- +---3-[o]-+ | Compiling ..\TEMP\A.C: + ^ |*Warning ..\TEMP\A.C 4: Ambiguous operators need parentheses + _ | Linking A.EXE: + _ | + _ | + v +-<___________________________________________________________________ +_______>-+ F1 Help | Accept the settings in this dialog box
Re: Beautiful code I wrote ;-)
by Anonymous Monk on Jul 14, 2008 at 04:41 UTC
    indeed.
Re: Beautiful code I wrote ;-)
by DrHyde (Prior) on Jul 11, 2008 at 10:09 UTC
    That's not beautiful. It's a poor attempt at obfuscation.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (10)
As of 2024-03-29 15:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found