« Backing Up Xen Guests via LVM | Main

Perl One Liners = Perl Is AWESOME!!!

Okay, so, I guess I am not a real blogger.  Which kind of stinks because this is a "tech" blog, and I'm not much of a geek either.  Anyway, it occurred to me that I wasn't updating my blog because I didn't really like the way it looked.  So, I grabbed another Movable Type style ("Minimalism", or something like that) and munged the style sheet to get a really wide page.  I think it is probably pretty unusual to have such a wide page, but right now, I am loving it.

But, none of that is why I am posting this particular entry.  Well, okay, the part about my site's style motivating me is probably the root cause for this entry.  REGARDLESS, from this moment on and forever, this entry will be about how much I love Perl one-liner's!  Or at least the one liner that helped me change my site's stylesheet.  Are you ready?!

[me@myhost ~]# perl -i.bak '-MPOSIX qw(floor)' \
>  -pe 'if (m/width *: *\d+ *px *;/){ $_ =~  s/(\d+)/floor( $1 * 1.8 )/ge; }' \
> site.css

So, here is what that line does. It calls perl (duh). "-i" sets up an in place edit of the file given as the last argument to the command, site.css, and it gives it an extension of ".bak." "-MPOSIX qw(floor)" imports the POSIX module with the "floor" subroutine (as in "use POSIX qw(floor)"). "-pe" says to treat the given perl statement(s) as a standalone script and to wrap them in a "while" loop, reading the file given into the "diamond" (<>) operator. Finally, the interesting part. The if statement checks if the line being parsed as part of the current iteration has a string in it that looks like "width: ###px;". If such a line is found, the next section searches for the number in the string and replaces it with a 1.8 multiple of itself rounded down to the nearest whole number. Notice the letter "e" at the end of the search and replace operator? The e tells the operator to wrap the replacement in an eval block to be executed as a piece of code such that the output replaces the string for which I searched. In this case, it allowed me to extend all of the hardcoded width statements in my stylesheet by 80%.

AWESOME!!!

Oh, by the way, and I may totally get this wrong, but the most useful Perl one-liner I have ever encountered in terms of effort vs. output is the following.

perl -pel filename

That one little line will convert all the line feeds in "filename" to the appropriate line feed for the platform you are running it on. Of course, most of the time this is most relevant for Windows, as it now seems most Linux editors gracefully handle DOS-style line feeds.

Enjoy.

TrackBack

TrackBack URL for this entry:
http://www.thouartpop.com/blog-mt/mt-tb.fcgi/6

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)