My Perl and Ruby Story

I’m not old enough to have grown attached to Perl. When I learned Perl people were already looking at Ruby and Python and proclaiming glorious victories. At that same time I saw people gripping Perl, not willing to leave their witty, terse confidant for those prettier, risky “New Kids on the Block.” I had dabbled with PHP and wanted more power. Perl was the natural choice. Previous experience, I thought, told me that I wanted a programming language where symbols, not words, held power. I quickly saw that in Perl. There were scripts nearly 50% symbols performing enticing feats with less characters then a Java Hello World program. So I took a look at Perl.

Summer Dreams Ripped at the Seams

As is the case with most Perl programmers I felt right at home. Perl has a tendency to do whatever you, the programmer, want’s it to do. “Do you want to suddenly make this variable in the middle of an if statement’s condition? Sure, why not, you’re the boss!” I instantly fell in love with its regular expression support. Learning to exploit the s/// statement alone has probably had far more impact on my entire programming career then any college course I’ve taken. The idea of a default variable was a poison I was happy to swallow. It just made so much sense.

# A Perl Script I wrote... Usage is not important
while (<>) {
   print "n$1: $2n" if /(.*?)s*w+ d+, (d+:d+)s*$/;
   print if ! /s*d+:d+s*$/;
}

My interest in Perl stopped when I saw its Object Oriented behavior. However, by that time I was far more interested in its scripting power. I took a very close look at Perl’s syntax and grammar. I knew every optional space… every optional semicolon… how to reduce an entire program to a single line and then reduce it further and further with dirty tricks. I ate up as many of Perl’s special variables as I could, spitting them out into my scripts. Why write “n” when $/ is two less characters… Essentially I learned to “Perl Golf.” It is the art of dwindling a simple script program down to as few characters as possible. This “black magic” side of Perl that got criticized by so many was a dangerous, but fun, sandbox that I spent my time in. Then, it all stopped.

$_=chr 123*rand,/[da-z]/i?$a.=$_:redo for 1..pop;print$a,$/

Normally, whenever I had a few weeks I would spend them learning a new programming language for fun. When I learned Perl I had three weeks off from school before I was to start my first Co-op. Time flew and my “fling” with Perl had to end. Little did I know that Perl left a rash on me that needed to be scratched. This disease made other programming languages look disgusting. Why is it so hard to parse files in Java, why is there no built-in regular expressions support in C++, what is wrong with these languages?!

A New Direction

Time went on. I was given another two weeks. Around that time I had made a decision that I would invest my personal time into web development. I spent hours and hours reading, learning, experimenting, grasping, producing, and all that jazz. It was reaching the end of those two weeks and one thing had been continually pounded into my head… Ruby on Rails was going to be big. I was young, I wanted in! With little time left in those two weeks I figured my time would be best spent focusing on Ruby and investing in Rails when I got more time. I honestly haven’t gotten around to learning Rails yet because I was so enamored with Ruby.

Learning Ruby was initially painful. I’ll admit it. I took a pass at it and was disgusted. To be honest, I can’t remember what was so painful. For one, I was intimidated by its block structure. Being as immature as I was, it felt too verbose… like a sore thumb in the language. But what the hell did I know? I still gave it a shot.

Why's Poignant Guide To Ruby

This book had a greater impact on me then just teaching me Ruby. It reaffirmed what I had seen from all over the web. Ruby users had a sense of humor, they tended toward creative expressiveness instead of technical explicitness, they invested in fun, they were not satisfied with the mundane. Also, the idea that a tutorial could be a story changed the way I thought about teaching in general. I made it far enough to drop my misapprehensions about Ruby’s syntax and embrace something Ruby did well at, Objects.

Perl Replacement

The more I used Ruby the more I realized that I wouldn’t need Perl. All my special variables were there. Replacing s/// with gsub was painful, but undeniably cleaner. I had matured slightly as a programmer and saw the need for code clarity and I now enjoyed Ruby’s block structure. When I challenged myself to create a simple Object Oriented program I saw how Ruby’s classes removed a lot of the repetition I normally put into Java classes. I was pleased.

I have to mention irb, Ruby’s interactive interpreter. This tool has proven invaluable to me. I almost always have an irb prompt open at all times. It is my calculator, my hacking companion, my playground, a debugger, and a friend. Perl lacks such an environment. I’ve had to really work to get the perlconsole working and Perl’s debug REPL just isn’t nearly the same. I’ve been able to expand and customize irb into an indispensable tool that can help me on any project. I think thats important, because with my Generation-X attention span, being able to copy.paste.sort.filter.reorder any text at a moments notice is “clutch.”

irb

Finally I was impressed with ruby gems. Need an html/xml parsing library and you’re unhappy with Ruby’s? Fine, `gem install hpricot`. Its so easy to download a new library, or even a new tool like `gem install cheat`. I liked the idea of distributing ruby scripts via gems that I even made my script a ruby gem (regex_replace). That way I can quickly download/install on any machine that I need it. The ability to build off of existing Ruby libraries is exciting.

The Beginning

As clichéd as that sounds, I feel like it can only get better. I’ve gotten comfortable enough with Ruby that I now write all my day-to-day scripts in it. I’m truly glad that I learned Perl, because it introduced me to the scripting world, and it is a unix staple. But, like so many others, it seems like there is a brighter path. I think thats more then enough for today.

Cheers.

A Little Inspiration

If you haven’t noticed, I normally start out each blog entry with a little anecdote. I try to let you know what made me write this. Its one of my favorite parts about writing these blog posts, because it can typically be outlined like:

  1. I run into a problem.
  2. I come up with an idea to solve the problem.
  3. I implement my idea and post the results.

Thats a lot of I’s… well, thats because it was me. Take a step back, remove those I’s, and there lies the framework, one of the true core of my motivational system. Find problems and solve them. This certainly isn’t something new for most people, but…

Sometime in the last year I “woke up.” I don’t know what I was doing before… I was certainly functioning just fine, but I wasn’t thinking like I am now. I’m much more “aware” now, and I feel like I have a lot of catching up to do. Mostly in philosophy, socially, and individually. So, when this happened I started following some sources and (partly because all of the technical blog posts that I want are too length to finish tonight) I’m going to start a new category “inspiration.” I’ll be posting links to material/media online that will hopefully inspire you to be more productive, be a better person, be more aware, and hopefully put a smile on your face.

I realize that for this to have any impact on you as an individual that you must have already “awoken” yourself. Congratulations, and keep up the great work.

Cheers.
– Joe P

 

My Favorite

Tony Robbin’s TED Talk, Why We Do What We Do – I’ll admit that even to this day I still haven’t completely grasped the significance of everything in this talk. But, this is clearly one of the most inspirational video’s I’ve ever seen.

And More

Randy Pausch Last Lecture: Achieving Your Childhood Dreams – This gained quite a bit of popularity. Its still something amazing to see.

The 7 Habits of Highly Effective People Audiobook (Free) by Stephen Covey – I just started listening to this (January 2009) and its pretty great. My High School Vice Principal gave every graduate in my class this book on graduation… I was not motivated enough then, but I am now.

The Junior Developer – My Number One Hurdle: Fear – This is one of a number of articles that impressed me from “The Junior Developer.”

How I Turned Down $300,000 from Microsoft to go Full-Time on GitHub – Tom Preston-Werner – Quote: When I’m old and dying, I plan to look back on my life and say “wow, that was an adventure,” not “wow, I sure felt safe.”

Spend Less Time Reading Blogs and Do Active Learning – I fell a little too deep into this habit. Reading everything there is to know on the subject, and thinking that I knew what I was talking about without ever having done any real work on the subject. Active learning is the most fundamental principle that drives this blog and why I challenged myself with this new years resolution.

Control Your Attention – Quote: Control of attention is the ultimate individual power. People who can do that are not prisoners of the stimuli around them. They can choose from the patterns in the world and lengthen their time horizons. This individual power leads to others. It leads to self-control, the ability to formulate strategies in order to resist impulses.

Updates to line.rb – Open to more suggestions

I was chatting with a friend the other day and he had some really good ideas concerning last week’s line.rb script. He wants to make an improved version. I look forward to seeing what he will come up with because he shared some great ideas. Well, I couldn’t help but implement them immediately in my version. His ideas also spurred a little creativity from me and I came up with a few new features as well. The usage is now looks like:


  # Check Cmd Line Args and Print Usage if needed
  if ARGV.size <= 1
    puts "usage: line [options] filename numbers"
    puts
    puts " options:"
    puts "   --silent or -s   Just print the line, without [#]"
    puts
    puts " number formats:"
    puts "   1-3              Prints lines 1 through 3"
    puts "   5                Prints line 5"
    puts "   -1               Prints the last line, (negative)"
    puts
    puts " extra formats:"
    puts "   ~5               Prints 2 (default) lines before and after 5"
    puts "   4~10             Prints 4 lines before and after 10"
    puts "   *7 or 8*         Prints all lines before or after the number"
    puts "   5/1              Prints 5 lines, then skips 1 line..."
    puts "   2:5/1            Starts at line 2, prints and skips..."
    puts
    exit 1

So there is some cool new syntax:

  • ~# – prints 2 lines before and after the given line number

  • #~# – prints the given number of lines before and after the given line number

  • *# – prints all of the lines before the given line number

  • #* – prints all of the lines after the given line number

  • #/# – is a print and skip option

  • #:#/# – allows you to provide an offset

Lets say you want to print every even line in a text file. With this script that is not a problem. The solution is: starting on the 2nd line, print 1 line, then skip 1 line. (line file 2:1/1):

Print only even lines using line.rb

I think these new formats are pretty neat. You can always access the latest version of the script on Github or in my ~/bin. I’m willing to change the syntax and introduce new concepts. Send suggestions my way by dropping a comment! Cheers.

Playing With Some More jQuery Plugins

I decided to play with some more jQuery plugins. I’m building up some experience, learning a lot, and having a ton of fun doing it. So, what did I decide to do this time? I added a sidebar to ~/bin. When you click on the logo in the top right an instructions panel will slide out on the right hand side of the screen. There is also a little magic going on with the logo.

sidebar

This sidebar has some neat animation so it was fun to put into the page. It is a modified version of the jQuery pageSlide plugin. To my pleasant surprise the plugin already had the capability to run callback functions before and after the transition is run. I added a property allowing for static html so I wouldn’t need to depend on an Ajax call. Also, the default behavior of the plugin is that clicking anywhere on the document, except in the sidebar, will cause the page to slide back to normal. This is okay except that I wanted a button for usability purposes to close the sidebar and also links in the sidebar (normal anchor tags) to work. That took a little creativity but I eventually got it:

      // Make it so if the user clicks in the pageslide, it won't close
      // Exception for given closers that may be in the pageslide
      $("#pageslide-slide-wrap").click(function(e){
        if ( $('a, ' + settings.closers).index( $(e.target) ) == -1 ) {
          return false;
        }
      });

 

Protecting the Innocent

I also wanted to play around with some jQuery lightboxes. The one that always comes to mind is facebox. For once I didn’t have to make any major changes to the source of this plugin, instead I made a few small tweaks to the CSS.

My goal here was to provide IE6 users with a simple little “Please Upgrade Your Browser” message. I went to work, learned a lot, and came up with the following: (to view this yourself go to ~/bin and paste “javascript:if_i_were_ie6()” in your URL bar, without the quotes!):

facebox browser upgrade warning

Sure that looked great, and it had a nice message, but it ended up looking disgraceful in IE6 itself! Rather then scrap the work I left it there, to prove the point to whatever few IE6 visitors I get. The facebox works perfectly in IE8 (I haven’t tried IE7) and so I can make use of what I’ve learned elsewhere I just hope that IE6 will go away soon. I said my goodbye already.

Adding Looping to a Content Slider

A few days ago I came across the wonderfully magnificent easySlider jQuery plugin. It makes sliding content vertically or horizontal drop dead simple using totally natural markup and CSS. I immediately worked it into the design of ~/bin (this animation was in my original design on paper) and it worked flawlessly. However, like the plugin’s title implies, it was and is meant to be simple and therefore lacks some features in order to gain ease of use.

I took some time to become more fluent in jQuery, and add some enhancements by modifying the plugin. One of those enhancements was looping, and is the topic of this article. I had no prior experience working with these types of galleries and implementing looping seemed like a fun idea. So here was the result of my tinkering:

How Do You Implement Looping?

Give yourself a minute to get creative. Develop some ideas and strategies on how you would take the following markup for the slides, and make it loop.

<div id="slider">
  <ul>
    <li>content here...</li>
    <li>content here...</li>
    <li>content here...</li>
  </ul>
</div>

I came up with two strategies that use a similar technique to implement the loops. The above loop is an implementation of one of these strategies, but I wanted to compare and contrast my two versions here, and hopefully get some reader feedback on different techniques!

Hidden Moves Strategy

This strategy actually involves physically moving unseen slides around in the DOM. By moving the slides in such a way that there is always the proper “next slide” and looping can continue forever in either direction without errors.

Hidden Moves Strategy

Instantaneous Jumps between Clones Strategy

This strategy actually involves cloning the first slide and adding it to the end of the list. This now makes the first and last slides exactly the same. When we need to handling transitions to and from these slides we can instantly jump between them, and the user is none the wiser.

Instantaneous Jumps Between Clones

Comparing the Pros and Cons of Each

Hidden Moves:

  • Requires no extra space (in theory).

  • Simple to implement moves. 1 line executed as a callback on “next” and before the transition if “prev”

  • Expensive. Requires moving slides on every transition. This is actual DOM manipulation. Sure in nearly all cases this is negligible but it could be a pain for large, complex slides.

  • Wouldn’t work on looping a single slide. Kinda useless though right?

  • Does it work? By taking a slide off of the front won’t everything shift? Yes, this could get tricky, I honestly haven’t tried it.

Instant Jumps:

  • Requires extra space to duplicate the first slide.

  • Simple to clone a slide. 1 line of jQuery.

  • 1 time cost to clone, never again is there a DOM Manipulation cost.

  • Has the ability to loop on a single slide.

  • Tricky code to handle when to jump. Nothing difficult, just messy.

  • Does it work? Yes, Its what I’m using above..

Thats it for my analysis. Do you have any suggestions?

Quickly Output Lines in a File

The other day I wanted a shell command to have somebody print out the 671st line of /etc/services on their computer. So I gave it some thought, then some more thought, scratched my head, and figured out that I couldn’t really think of a shell command that does that. A google search came up with a few `sed` and `awk` examples but I honestly found those to be a bit awkward for something that should be super simple. So I wrote my own script.

After writing the script to print out a single line, I soon found it made a lot of sense to include ranges. Taking advantage of Ruby I can even print lines from the end with negative numbers. So I spent a few minutes to clean up the script and make it a little more reusable, add some formatting, and cleaner. Here was the result:

line sample usage

line is now the latest addition to my ~/bin.

Also, in case you wanted to use this in a shell script or via piping, there is a `–silent` or `-s` switch that you can use that removes all of the special formatting, and prints only the specified lines. Much nice for scripts. (See the highlighted line in the image below). Enjoy!

line source

So what exactly is line 671 of /etc/services? On my mac it is:

line 671 of /etc/services

~/bin – Tilde Bin

So I wanted to do a little something over break. I had no idea what I would do, until I came across this article taking a look at the blueprint css framework. I had heard plenty of talk about this css framework, and other grid frameworks, and decided to give it a shot.

So I had something new I wanted to work with, what was the site actually going to be? I gave it a few minutes thought and ended up with an idea that satisfied my semi-recent Internet philosophy:

When I have something worth spreading I should write it on my blog or turn it into a webpage. This way when people ask me about it, or if I need to present the information to someone, I can just point them to that single source. This saves me from having to type and retype the same information over and over for different people. A single “master” source with the most up to date information is always optimal.

With that in mind, I decided to whip up a simple site to showcase the scripts that are in my “tilde bin” folder. Scripts that I wrote and use frequently that others might find useful. Sure I’ll still blog about them, but for those who want to download them its so much faster to point them to ~/bin instead of having them scour my blog.

~/bin

And thus ~/bin was born.

Sidenotes

I was quite satisfied with the result. It took only 24 hours from Conception to Creation. I made use of Blueprint and jQuery (AJAX and animation) to create a pretty fresh website. Sure its pretty basic but I felt comfortable the entire way through, and I loved every minute of it. I’m hoping that when Ruby on Rails 3 is released, if I have some spare time, I’ll convert it and include a small admin dashboard.

As of two years ago I’ve decided to get pretty serious with my New Years Resolutions. This year (like last year) I have a few ideas I’m tossing around. It will be a few weeks until I settle on one. Typically the resolutions will help me improve my health or lifestyle. One of the ideas I’m tossing around is blogging at least once per week. Compared to the other alternatives this is certainly the most fun. It has a hint of a challenge and its pretty doable. Let me know what you think!

search