macdevcenter.com
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button

Using Perl to Manage Plist Files, Part 2
Pages: 1, 2, 3, 4, 5, 6

Here is a simple example that creates a dictionary filled with an int, boolean, string, float, and date.


#!/usr/bin/perl

use Foundation;
use lib "/Users/yourname/Desktop/";
require "perlplist.pl"; # for cocoaInt, etc, and cocoaDictFromPerlHash

my %hash = (
  int=>cocoaInt( 1 ),
  boolean=>cocoaBool( 1 ),
  string=>"1",
  float=>cocoaFloat( 1.0 ),
  date=>cocoaDate( 1 ),
);

my $plist = cocoaDictFromPerlHash( %hash );
$plist->writeToFile_atomically_( "/tmp/example.xml", "0" );
open ( FILE, "</tmp/example.xml" ) or die "Can't open\n";
print <FILE>;
close ( FILE );

Here is an example that creates a Plist file that we can use to submit a simple Xgrid batch job. To see an XML representation of this Plist file, look at the Xgrid 1.0 man page.


#!/usr/bin/perl

use Foundation;
use lib "/Users/yourname/Desktop/";
require "perlplist.pl"; # for perlValue

my @arguments = ( "6", "2005" ); # start with the deepest objects first

my %task0 = (
	command=>"/usr/bin/cal",
	arguments=>\@arguments,
);

my %tasks = (
	0=>\%task0,
);

# the last object is the parent dictionary
my %hash = (
	name=>"Cal Job",
	taskSpecifications=>\%tasks,
);

my $plist = cocoaDictFromPerlHash( %hash );
$plist->writeToFile_atomically_( "/tmp/sample_batch.xml", "0" );

system "xgrid -job batch /tmp/sample_batch.xml";

A final note, when nesting arrays or hashes in arrays or hashes, you must add a backslash:

arguments=>\@arguments

and

taskSpecifications=>\%tasks

Final Thoughts

I hope the Plist management subroutines shown in this article will be useful. I especially hope I have been able to expose Perl scripters to enough Cocoa that they can come up with more uses for the PerlObjCBridge. Cocoa is a wonderful language. Methods like dictionaryWithContentsOfFile_ and writeToFile_atomically_ are excellent examples of why you would want to include a little Cocoa in Perl scripts.

In learning the PerlObjCBridge, I was surprised how few code examples were publicly available. If you do come up with your own code, I encourage you to put the code online. If you desire to take Cocoa and Perl a step further, check out Camelbones.

Finally, I'd just like to thank Charles Parnot for his help with the article and understanding the PerlObjCBridge. And I'd like to thank David Kramer for giving me the idea that led to this article: using the PerlObjCBridge to parse the output of the Xgrid command-line tool, which is formatted as ASCII Plist.

James Reynolds is a member of the University of Utah's Student Computing Labs Mac Group. His main duty is the deployment of Mac OS X. Most of his responsibilities include the OS customizations, scripts, and security of the Mac OS X lab and kiosk computers supported by SCL.


Return to the Mac DevCenter