-
Notifications
You must be signed in to change notification settings - Fork 4
Home
oalders edited this page Sep 21, 2011
·
10 revisions
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.
###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];
###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];
Perl:
$list{'foo'} = 'baz';
Objective-C:
[list setObject:baz forKey:@"foo"];
###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
Perl:
$foo =~ s{bar}{baz}g;
Objective-C:
foo = [foo stringByReplacingOccurrencesOfString:@"bar" withString:@"baz"];
Perl:
$filename .= '.html';
Objective-C:
fileName = [fileName stringByAppendingString:@".html"];
Perl:
if ( -e $file_path ) {
}
Objective-C:
if ( ![ [NSFileManager defaultManager] fileExistsAtPath:filePath] ) {
}
Perl:
$foo =~ s{\A\s+(.*)\s+\z}{$1};
$foo =~ s{\s+}{ }g;
Objective-C:
foo = [foo stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
Perl:
my @foo = split " ", $bar;
Objective-C
NSArray *foo = [bar componentsSeparatedByString:@" "];
Perl:
my $length = length( $bar );
Objective-C
NSInteger *length = [bar length];