Saturday, November 14, 2009

Perl snippets

I have a bad habit of writing down useful tricks/snippets and then losing the piece of paper. I've decided to start using this entry as a kind of jotter, to be added to at regular intervals. Here we go...

To take an array that only contains numbers, leave out duplicates and sort in numeric order (the default sort function orders by ASCII value) :

#!/usr/bin/perl

my @array = (1, 3,4, 5, 4, 6,7,4, 20 , 21, 20, 19, 19,18);

my %hash = map { $_, 1 } @array;
# or a hash slice: @hash{ @array } = ();
# or a foreach: $hash{$_} = 1 foreach ( @array );

my @unique = keys %hash;
my @sorted =sort { $a<=>$b; } @unique;

foreach $item(@sorted) {
print " $item \t";
}
print "\n";


To work through lines fed in from a file, ignoring blank lines but outputting the first word of the line otherwise:

while (<>) {
next if /^$/;
($primero)=split;

{print "Found: $primero \n"; }
}


How many elements in an array ? (ok, basic stuff here :) )

my @fruits = ("apples", "oranges", "guavas", "passionfruit", "grapes");

my $last = $#fruits +1; # ie last element of index +1

Or simply force the array to a scalar context to find out the number of elements:

my $last = @fruits;

No comments:

Post a Comment