From PHP to Perl


PHP array_unique in Perl

Posted in Other by gosukiwi on March 6, 2008
Tags: , ,

Well this function is very handy when you are working with flatfiles, or for example you dont have a category table on your mysql database, so entries have repeatead categories.

What the function array_unique does, is return an array without the repeated elements given in the array you gave as argument.

For example:

<?php
$array = array(1,2,1,3,4,1,2,6,4,5,1);
$array = array_unique($array);
sort($array);
print_r($array);
?>

That will print

Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )

It deletted repeated elements, now, how to do that in perl?
Well that function does not exists in perl, anyways, you can create it, its not very hard… Here are some examples, this is the one i made

sub array_unique
{
my @list = @_;
my %finalList;
foreach(@list)
{
$finalList{$_} = 1; # delete double values
}
return (keys(%finalList));
}

It works exactly the same as PHP’s array_unique, someone at Cafe PM also suggested this one, which is shorter but to be honest i dont understand it much

sub array_unique
{
my %seen = ();
@_ = grep { ! $seen{ $_ }++ } @_;
}

That function also works the same as the one before, and the code in perl would be

#!/usr/bin/perl

use CGI’:all’;
use strict;

# Code…
sub array_unique
{
my %seen = ();
@_ = grep { ! $seen{ $_ }++ } @_;
}
# More code….

my @array = (1,2,1,3,4,1,2,6,4,5,1);
@array = sort(array_unique(@array));
print header, “@array”;

And that will print

1 2 3 4 5 6

Well, thats it, enjoy!

Advertisements

4 Responses to 'PHP array_unique in Perl'

Subscribe to comments with RSS or TrackBack to 'PHP array_unique in Perl'.

  1. Burg said,

    b => sub array_unique
    {
    my @list = @_;
    my %finalList;
    foreach(@list)
    {
    $finalList{$_} = 1; # delete double values
    }
    return (keys(%finalList));
    }

    it is executed quicker than:
    a => sub array_unique
    {
    my %seen = ();
    @_ = grep { ! $seen{ $_ }++ } @_;
    }

    Rate b a
    b 11737/s — -23%
    a 15299/s 30% —

    b best algorithm 🙂

  2. assasiner said,

    Nice 😀 i didnt benchmark hehe

  3. zazazaz said,

    Burg but it breaks array order = bad.

  4. nana said,

    Why do we have to create a new array @finalList ? Can’t we just delete values in the initial array @lines ?


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: