Cocoa, Objective-C, and Perl
All computer languages have their advantages and disadvantages. Perl is a great language for parsing and massaging text. If you are writing a Cocoa, Objective-C program, and you need to parse and massage text, you may want to hand that task off to some Perl code. This can be easily done. OS X comes with Perl installed, and you can have a Perl program as one of the resources in your Cocoa application. Following is some sample Objective-C code and Perl code that illustrates how to launch a Perl program that will write a temporary file that can then be read by your Objective-C code:
Here is the Objective-C code to set up and launch the perl program:
// define your temp file
FILE *fp;
NSMutableString *tmpPath = [[NSMutableString alloc] initWithString:@”"];
[tmpPath setString:@"tempfilepath/tempfilename"];
// this is the path to your perl program
plPath = [thisBundle pathForResource:@"perlpgm" ofType:@"pl"];
// array to pass arguments to your perl program
NSMutableArray *argArray = [[NSMutableArray alloc] initWithObjects:plPath,tmpPath,nil];
// launch the perl program & wait for it to finish
[[NSTask launchedTaskWithLaunchPath:[NSString stringWithFormat:@"/usr/bin/nice"] arguments:argArray] waitUntilExit];
// open the temp file that has been written by the perl program
fp = fopen([tmpPath UTF8String], “r”);
// process the contents of the temp file here
fclose(fp);
// remove the temp file when you’re done
NSFileManager *manager = [NSFileManager defaultManager]
[manager removeFileAtPath:tmpPath handler:nil];
And here is what the code in your perl program will look like:
$tempFile = shift;
open ( TMPFILE, “$tempFile” ) || print STDERR “problem opening $tempFile\\n”;
# do your text massaging here and write the temp file.
close TMPFILE;
Of course you can also use STDIN and STDOUT if you don’t want to write a temporary file.
May 15th, 2012 at 5:18 am
Thank you for an excellent and very useful post. This post was like finding a PERL in a pile of worthless pebbles!
Thanks