Skip to content
This repository

Home 

oalders edited this page · 10 revisions

Pages 1

Clone this wiki locally

This wiki is intended to be useful as a reference for Perl hackers who are looking to pick up a bit of Objective-C. All Objective-C code samples displayed here are to be accompanied by the (roughly) equivalent Perl code.

Arrays

Access the 3rd element of an Array:

Perl:

$array[2]

Objective-C

[array objectAtIndex:2]

Add an element to an Array:

Perl:

push @array, $foo;

Objective-C

[array addObject:foo];

Create a Mutable Array:

Perl:

my @array = ();

Objective-C

NSMutableArray *array = [ [NSMutableArray alloc] init];

Get size of array

Perl:

my $size = @array;

Or force scalar context:

my $size = scalar @array;

Objective-C:

//In this case array must be an NSArray object    
NSInteger *count = [array count];

Hashes

Initialize a hash with data:

Perl:

my %list = ( foo => $bar, one => $two );

Objective-C (mutable)

NSMutableDictionary *list = [ [NSMutableDictionary alloc] initWithObjectsAndKeys: bar, @"foo", two, @"one", nil];

Objective-C (immutable, ie fixed number of keys):

NSDictionary *list = [ [NSDictionary alloc] initWithObjectsAndKeys: bar, @"foo", two, @"one", nil];

Set a hash value

Perl:

$list{'foo'} = 'baz';

Objective-C:

[list setObject:baz forKey:@"foo"];

Print

Formatted print statements.

Perl:

print sprintf("We are open %i days per %s", 7, 'week');

Objective-C:

NSLog(@"We are open %i days per %@", 7, @"week");

More info on string format specifiers in Objective-C

Find and Replace

Perl:

$foo =~ s{bar}{baz}g; 

Objective-C:

foo = [foo stringByReplacingOccurrencesOfString:@"bar" withString:@"baz"];

String Concatenation

Perl:

$filename .= '.html'; 

Objective-C:

fileName = [fileName stringByAppendingString:@".html"];

File Exists?

Perl:

if ( -e $file_path ) { 
}

Objective-C:

if ( ![ [NSFileManager defaultManager] fileExistsAtPath:filePath] ) {
}

Trim Whitespace

Perl:

$foo =~ s{\A\s+(.*)\s+\z}{$1};
$foo =~ s{\s+}{ }g;

Objective-C:

foo = [foo stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

Split

Perl:

my @foo = split " ", $bar; 

Objective-C

NSArray *foo = [bar componentsSeparatedByString:@" "];

String Length

Perl:

my $length = length( $bar ); 

Objective-C

NSInteger *length = [bar length];
Something went wrong with that request. Please try again.