Wednesday, June 3, 2009

Perl => Micro$haft Rant

The other day I tweeted in a mad fury with very little details as to the source of my frustrations. To enlighten my Twitter followers, here is the email which served as the source of such anger:
It turns out that when you pass an array as an argument in Perl, it flattens the array, thus giving you a lot of arguments.

Example:
@array = (1, 2, 3);
Print_array( @array );

Sub print_array() {
My ($1, $2, $3) = @_;
Print "$1\n";
Print "$2\n";
Print "$3\n";
}


Rather Than:
@array = (1, 2, 3);
Print_array( @array );

Sub print_array() {
My @nums = shift;
Foreach my $num (@nums) {
Print "$num\n";
}
}


Unfortunately this really screws things up when you want to pass an array along with some scalars.

Such As:
@array = (1, 2, 3);
$sum = 6;
Print_math( @array, $sum );

Sub print_math() {
My (@nums, $math) = @_;
Print $nums[0].'+'.$nums[1].'+'.$nums[2].'='.$sum;
}


Working Solution:
@array = (1, 2, 3);
$sum = 6;
Print_math( \@array, $sum );

Sub print_math() {
My ($num_array, $math) = @_;
My @nums = @$num_array;
Print $nums[0].'+'.$nums[1].'+'.$nums[2].'='.$sum;
}


Ignore the auto-caps. Have I ever mentioned I hate M$ products?

Microsoft: "We're so smart we know how to capitalize sentences. You must be too stupid to know how to do this like we do. We will help you capitalize your sentences."

Me: "But I'm not typing sentences..."

Microsoft: "What do you mean? People only type sentences in their emails. No one except us understands code or other non-sentence based writing."

Me: "Go #@$* yourself Micro$haft! You're #@$*ing retarded! You're 'increase indent' button claims it can't work with plain text emails even though I clearly have tabs in this plain text email because I had to type everyone @*%&@() one of them myself!"

Labels:

2 Comments:

Blogger draegtun said...

Hopefully the code in this comments won't get screwed up!

Two other ways to do that sub are....

sub print_math {
my @nums = @{ $_[0] };
my $math = $_[1];
print $nums[0].'+'.$nums[1].'+'.$nums[2].'='.$sum;
}

AND

sub print_math {
my ( $nums, $math ) = @_;
print $nums->[0].'+'.$nums->[1].'+'.$nums->[2].'='.$sum;
}

June 5, 2009 at 4:55 PM  
Blogger draegtun said...

BTW... put "use strict;" & "use warnings"; in your code because u'll notice there are a few bugs in there & these comments ;-)

June 5, 2009 at 4:58 PM  

Post a Comment

Subscribe to Post Comments [Atom]

<< Home