AndreiMotinga AndreiMotinga - 5 months ago 9
Perl Question

How do I sort an array in Perl if not all of the elements in the array are defined?

How do I sort an array if not all of the elements in the array are defined?

my @names;
$names[0] = "andrei";
$names[1] = "serghei";
$names[7] = "valerii";
$names[10] = "alexandr";

@names = sort @names; # aint working.


I apologize guys, I just don't get how to post questions here properly. I tried the FAQ, I just don't get it.

Answer
use strict;
use warnings;
use autodie;
use feature qw(say);

my @names;
$names[0]  = "andrei";
$names[1]  = "serghei";
$names[7]  = "valerii";
$names[10] = "alexandr";

@names = sort grep { defined } @names;

for my $name ( @names ) {
    say $name;
}

The grep { defined } takes @names and removes all the undefined values from @names.

If you don't want to remove the undefined stuff, you can do this:

#! /usr/bin/env perl
#
use strict;
use warnings;
use autodie;
use feature qw(say);

my @names;
$names[0]  = "andrei";
$names[1]  = "serghei";
$names[7]  = "valerii";
$names[10] = "alexandr";

no warnings qw(uninitialized);
@names = sort @names;
use warnings qw(uninitialized);

for my $name ( @names ) {
    say $name if defined $name;;
}

The no warnings qw(initialized); will turn off uninitialized warnings. I know that I'll run into trouble with unitialized warnging with sort, so I simply turn off the uninitialized warnings, and turn them right back on right after the sort.

Comments