Pages

Showing posts with label perl. Show all posts
Showing posts with label perl. Show all posts

Thursday, August 4, 2011

Create a Perl Module Skeleton Using h2xs

The h2xs binary is used to convert C header files to Perl extensions, but it can also be used to create a Perl module template. Creating modules this way will save you a lot of time and make sure that your module is setup up correctly for submission to CPAN.

You can create your own module skeleton with h2xs using:

h2xs -A -X -n My::Module

This will create a directory called My-Module with the following files:

My-Module/lib/My/Module.pm
My-Module/Makefile.PL
My-Module/README
My-Module/t/My-Module.t
My-Module/Changes
My-Module/MANIFEST

Module.pm is your actual module, which you will edit and add your desired functionality into. Your module can be installed on your system by following these steps:

perl Makefile.PL

This creates the makefile

make test

This executes all tests, assuming you have created some.

make install

This will install the module in your system, you may have to execute this line as super user.

You can package up your module for submission to CPAN, or other distribution means by typing:

make tardist

This will create My-Module-0.01.tar.gz inside your project directory.

Monday, June 13, 2011

Programmatically Calculate Battery Charge

This is a cool way to determine what the charge of your battery is on a Mac laptop using Perl. Basically we execute the command ioreg -l in a shell and filter out all the results except MaxCapacity and CurrentCapacity, then we use regular expressions to parse out just the values. From there it's just a matter of calculating what percentage current capacity is of the max capacity and printing out the results.

#!/usr/bin/perl -w

my $MaxCapacity = `ioreg -l | grep 'MaxCapacity'`;
my $CurrentCapacity = `ioreg -l | grep 'CurrentCapacity'`;

$MaxCapacity =~ /(\d+)/;
$MaxCapacity = $1;

$CurrentCapacity =~ /(\d+)/;
$CurrentCapacity = $1;

printf("Battery Charge: %d %%" . "\n", (($CurrentCapacity / $MaxCapacity) * 100));

Executing the script produces something similar to:

Battery Charge: 90 %

If you execute this on a Mac that doesn't have a battery you will probably get a division by zero error.