View Category

Define an empty list

Assign the variable "list" to a list with no elements
perl
@list = ();

Define a static list

Define the list [One, Two, Three, Four, Five]
perl
@list = qw(One Two Three Four Five);
@list = ('One', 'Two', 'Three', 'Four', 'Five');

Join the elements of a list, separated by commas

Given the list [Apple, Banana, Carrot] produce "Apple, Banana, Carrot"
perl
print join ', ', qw(Apple Banana Carrot);
# Longer and less efficient than join(), but illustrates
# Perl's foreach operator, which can be useful for
# less trivial problems with lists

@list = ('Apple', 'Banana', 'Carrot');
foreach $fruit (@list) {
print "$fruit,";
}
print "\n";
my @a = qw/Apple Banana Carrot/;
{
local $, = ", ";
print @a
}
print "\n";
my @a = qw/Apple Banana Carrot/;
{
local $" = ", ";
print "@a\n";
}

Join the elements of a list, in correct english

Create a function join that takes a List and produces a string containing an english language concatenation of the list. It should work with the following examples:
join([Apple, Banana, Carrot]) = "Apple, Banana, and Carrot"
join([One, Two]) = "One and Two"
join([Lonely]) = "Lonely"
join([]) = ""
perl
sub myjoin {
$_ = join ', ', @_;
s/, ([^,]+)$/ and $1/;
return $_;
}


# Note: I don't think this meets the spec --Geoff
sub myjoin {
if ($#_ < 2) {
return join ' and ', @_;
} else {
return join(', ', @_[0..$#_-1]) . ' and ' . $_[-1];
}
}

# Note: I don't think this meets the spec --Geoff
# Previous "myjoin()" responses don't meet the spec of including
# the final comma before the "and" if the list has more than
# two elements...this is one way to meet that spec...it may
# not be the most efficient...

sub AnotherMyJoin {
my @list = @_;

if ($#list == -1) {return}
elsif ($#list == 0) {return $list[0]}
elsif ($#list == 1) {return $list[0].' and '.$list[1]}
else {
return join(", ", @list[0..$#list - 1]) . ', and '. $list[$#list];
}
}
# This is the long way, but it's kind of fun
# It illustrates the use of Perl's reverse()
# operator to work our way through the list
# elements backwards...I wrote this one before
# getting smart and looking at some of the other
# algorithms from the other languages. Still,
# it is only 12 lines of code vs 9 for my other
# solution if you disregard the comments.

sub myjoin {
my @list = reverse(@_); # Reverse original order of elements
my $retval;

# Make our exit here if we were passed an empty list
if ($#list == -1) {return}

# Loop through reversed elements in end-to-start order
for (0..$#list) {
# Add the reversed form of each element plus a space char
$retval .= reverse($list[$_]).' ';

# Add 'and' to lists with two or more elements
# placing it in between final and 'next to final'
$retval .= "dna " if ($#list > 0 and $_== 0);

# Add ',' to each element as long as there are more
# than two elements and the current element isn't the
# final element
$retval .= "," if ($#list > 1 and $_ != $#list);
}

# Remove what will end up as an extraneous leading space
chop($retval);

# Done looping, now reverse things back into correct order and return
$retval = reverse($retval);
return($retval);
}
# Yes, this doesn't meet the spec, the spec is flawed
# the serial comma (Oxford comma) is not required in a list
sub english_join {
return join(', ', @_[0..$#_-1])
. ($#_ ? ' and ' : '' )
. $_[-1];
}

Produce the combinations from two lists

Given two lists, produce the list of tuples formed by taking the combinations from the individual lists. E.g. given the letters ["a", "b", "c"] and the numbers [4, 5], produce the list: [["a", 4], ["b", 4], ["c", 4], ["a", 5], ["b", 5], ["c", 5]]
perl
@letters = qw(a b c);
@numbers = (4, 5);
@list = map { $number=$_; map [$_, $number], @letters; } @numbers;
@letters = qw(a b c);
@numbers = (4, 5);

for $number (@numbers) {
for $letter (@letters) {
push @list, [$letter, $number];
}
}

From a List Produce a List of Duplicate Entries

Taking a list:
["andrew", "bob", "chris", "bob"]

Write the code to produce a list of duplicates in the list:
["bob"]
perl
my @input = ("andrew", "bob", "chris", "bob", "bob");

my %input_count;
my @output = grep { $input_count{$_}++; $input_count{$_} == 2 } @input;

Fetch an element of a list by index

Given the list [One, Two, Three, Four, Five], fetch the third element ('Three')
perl
qw(One Two Three Four Five)[2];
@list = qw(One Two Three Four Five);
$list[2];

Fetch the last element of a list

Given the list [Red, Green, Blue], access the last element ('Blue')
perl
qw(Red Green Blue)[-1];
@list = qw(Red Green Blue);
$list[-1];

Find the common items in two lists

Given two lists, find the common items. E.g. given beans = ['broad', 'mung', 'black', 'red', 'white'] and colors = ['black', 'red', 'blue', 'green'], what are the bean varieties that are also color names?
perl
@beans = qw(broad mung black red white);
@colors = qw(black red blue green);
@seen{@beans} = ();
for (@colors) {
push(@intersection, $_) if exists($seen{$_});
}
print join(', ', @intersection);
@beans = qw(broad mung black red white);
@colors = qw(black red blue green);

my %colors_hash = map { $_ => 1 } @colors;
my @intersection = grep { $colors_hash{$_} } @beans;
print join(', ', @intersection),"\n";
@beans = qw/broad mung black red white/;
@colors = qw/black red blue green/;

print join ', ', grep { $_ ~~ @colors } @beans;

Display the unique items in a list

Display the unique items in a list, e.g. given ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18], display the unique elements, i.e. with duplicates removed.
perl
@ages = (18, 16, 17, 18, 16, 19, 14, 17, 19, 18);
@seen{@ages} = ();
@unique = keys %seen;
print join(', ', @unique);
@ages = (18, 16, 17, 18, 16, 19, 14, 17, 19, 18);
@unique = grep(!$seen{$_}++, @ages);
print join(', ', @unique);
@ages = (18, 16, 17, 18, 16, 19, 14, 17, 19, 18);
print join(', ', grep(!$seen{$_}++, @ages));
@ages = (18, 16, 17, 18, 16, 19, 14, 17, 19, 18);
for (@ages) {
push(@unique, $_) unless $seen{$_}++;
}
print join(', ', @unique);
use List::MoreUtils qw(uniq);

@ages = (18, 16, 17, 18, 16, 19, 14, 17, 19, 18);
print join(', ', uniq(@ages));

Remove an element from a list by index

Given the list [Apple, Banana, Carrot], remove the first element to produce the list [Banana, Carrot]
perl
@list = qw(Apple Banana Carrot);
shift @list;
@list = qw(Apple Banana Carrot);
$offset = 0;
splice(@list, $offset, 1);

Rotate a list

Given a list ["apple", "orange", "grapes", "bananas"], rotate it by removing the first item and placing it on the end to yield ["orange", "grapes", "bananas", "apple"]
perl
@list = qw(apple, orange, grapes, bananas);
push @list, shift @list;
@list = qw(apple orange grapes bananas);
@list = @list[1..$#list,0];

Gather together corresponding elements from multiple lists

Given several lists, gather together the first element from every list, the second element from every list, and so on for all corresponding index values in the lists. E.g. for these three lists, first = ['Bruce', 'Tommy Lee', 'Bruce'], last = ['Willis', 'Jones', 'Lee'], years = [1955, 1946, 1940] the result should produce 3 actors. The middle actor should be Tommy Lee Jones.
perl
my @first = ('Bruce', 'Tommy Lee', 'Bruce');
my @last = ('Willis', 'Jones', 'Lee');
my @years = (1955, 1946, 1940);

my @actors;

my $max = scalar @first;
for my $index (0 .. $max) {
push @actors, [ $first[$index], $last[$index], $years[$index] ];
};

List Combinations

Given two source lists (or sets), generate a list (or set) of all the pairs derived by combining elements from the individual lists (sets). E.g. given suites = ['H', 'D', 'C', 'S'] and faces = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'], generate the deck of 52 cards, confirm the deck size and check it contains an expected card, say 'Ace of Hearts'.
perl
@suites = qw(H D C S);
@faces = qw(2 3 4 5 6 7 8 9 10 J Q K A);
@deck = map { $suite=$_; map $suite.$_, @faces; } @suites;
print 'checking deck size: ' . (@deck == 52 ? 'pass' : 'fail') . "\n";
print 'deck contains "Ace of Hearts": ' . (grep(/^HA$/, @deck) ? 'true' : 'false') . "\n";

Perform an operation on every item of a list

Perform an operation on every item of a list, e.g.
for the list ["ox", "cat", "deer", "whale"] calculate
the list of sizes of the strings, e.g. [2, 3, 4, 5]
perl
my @list = qw{ox cat deer whale};

my @lengths = map {length($_)} @list;

print "@list\n";
print "@lengths\n";

Split a list of things into numbers and non-numbers

Given a list that might contain e.g. a string, an integer, a float and a date,
split the list into numbers and non-numbers.
perl
use Scalar::Util qw(looks_like_number);
my @things = ('hello',25,3.14,scalar(localtime(time)));
my @numbers;
my @others;
for ( @things ) {
if ( looks_like_number $_ ) {
push @numbers, $_;
} else {
push @other, $_;
}
}

Test if a condition holds for all items of a list

Given a list, test if a certain logical condition (i.e. predicate) holds for all items of the list.

Test if a condition holds for any items of a list

Given a list, test if a certain logical condition (i.e. predicate) holds for any items of the list.