12/4/2017 - 4:52 PM

List Functions (grep, split, join, map, sort)

These operate on lists, here are some commonly used ones.

# == GREP (Global Regular Expression Print) ==
# looks through an array or list and returns the number of times the regex is found
my $found = grep/a/, ("ant", "bug", "cat"); # returns 2 because "a" was found twice
# for arrays, grep will return the array with only the matched elements left inside
my @found = grep/a/, ("ant", "bug", "cat",);
# would leave the array like this
@found = ("ant", "cat");

# == SPLIT ==
# Separates a string using a delimiter pattern and returns the separated array
my @array = split/,/, "one, two, three, four";
# Results in @array having the values ("one", "two", "three", "four");

# == JOIN ==
# this will return the string of values separated by the join string
my $text = join ",", @array; #separated the values in @array with commas

# == MAP == 
# takes a list as an argument and performs a user-defined operation on each element in turn.
# to change an array to all upper case:
my @upper = map{uc($_)} @array; # each element is assinged to the default variable $_ 
# they are then converted to uppercase, map has then made and returned a new list in all uppercase which is then assigned to @upper

# == SORT ==
# arranges any list into a sorted order. More information and advanced use in documentation
print sort("gamma", "beta", "alpha"); # Returns alphabetagamma - use join for commas:
print(join",", sort("gamma", "beta", "alpha")), "\n"; # returns "alpha, beta, gamma"
# the sort function can sort a list according to virtually any sort criterion you can imagine