4. Working with Data

Created Thursday 17 April 2014

Working with Strings

chop() and chomp()

chop (defaults to $_)
chop VARIABLE
chop ( LIST )
chomp (defaults to $_)
chomp VARIABLE
chomp ( LIST )

my $name = 'Ovid';
my $last = chop $name; # $last is now set to 'd' and $name is 'Ovi'

chr() and ord()

chr (defaults to $_)
chr NUMBER
ord (defaults to $_)
ord STRING

index() and rindex()

index STR, SUBSTR, POSITION
index STR, SUBSTR
rindex STR, SUBSTR, POSITION
rindex STR, SUBSTR

my $word = 'miminypiminy';
my $first = index $word, 'iminy';
my $second = index $word, 'iminy', $first + 1;
my $last = rindex $word, 'iminy';
my $not_last = rindex $word, 'iminy', $last - 1;

lc(), lcfirst(), uc(), and ucfirst()

lc (defaults to $_)
lc EXPR
lcfirst (defaults to $_)
lcfirst EXPR
uc (defaults to $_)
uc EXPR
ucfirst (defaults to $_)
ucfirst EXPR

print ucfirst lc 'PERL';

length()

length (defaults to $_)
length EXPR

pack() and unpack()

pack TEMPLATE, LIST
unpack TEMPLATE, VARIABLE
unpack TEMPLATE

my $record = '20080417john 39552027';
my ( $hired, $user, $emp_number, $dept ) = unpack 'A8A8A5A3', $record;
print "Hired: $hired\nUser: $user\nEmp#: $emp_number\nDept: $dept\n";
This will print:
Hired: 20080417
User: john
Emp#: 39552
Dept: 027

print()

print (defaults to $_)
print FILEHANDLE LIST
print LIST

my $customer = 'Alex';
print "Customer: $customer\n";

sprintf() and printf()

sprintf FORMAT, LIST
printf FILEHANDLE FORMAT, LIST
printf FORMAT, LIST

my @musketeers = qw( Aramis Athos Portos );
printf "%s,%s\n", @musketeers; # prints "Aramis,Athos"
my $two_musketeers = sprintf "%s,%s", @musketeers; # $two_musketeers is now "Aramis,Athos"

substr()

substr EXPR,OFFSET,LENGTH,REPLACEMENT
substr EXPR,OFFSET,LENGTH
substr EXPR,OFFSET

my $string = 'halfhearted';
my $substr = substr $string, 0, 4, 'hard';
print "$substr\n$string\n";

tr/// and y///

VARIABLE =~ tr/SEARCHLIST/REPLACEMENT/cds
VARIABLE =~ y/SEARCHLIST/REPLACEMENT/cds

To replace all commas in a string with tabs:
my $string = "Aramis,Athos,Portos";
$string =~ tr/,/\t/;
print $string;
To make all vowels lowercase:
$string =~ tr/AEIOU/aeiou/;
Specifying a range:
$string =~ tr/A-Z/a-z/;

Repetition Operator: x

STRING x INTEGER
(STRING) x INTEGER

my $santa_says = 'ho' x 3.7; # A typo with '.7'??? There is an explanation then that Perl does casting to int in such cases
print $santa_says;

To assign a single value multiple times to a list, force list context:
my $ho = 'ho';
my @santa_says = ($ho) x 3;

Concatenation Operator: .

STRING . STRING

Autoincrement and Autodecrement Operators: ++ and--

++VARIABLE
--VARIABLE
VARIABLE++
VARIABLE--

my $letter = "a";
$letter++;
print $letter; # Will print 'b'

perldoc perlop says:
If, however, the variable has been used in only string contexts since it was set, and has a value that is not the empty string and matches the pattern "/^[a-zA-Z]*[0-9]*\z/", the increment is done as a string, preserving each character within its range, with carry:
print ++($foo = '99'); # prints '100'
print ++($foo = 'a0'); # prints 'a1'
print ++($foo = 'Az'); # prints 'Ba'
print ++($foo = 'zz'); # prints 'aaa'
...
Note that just as in C, Perl doesn't define when the variable is incremented or decremented. You just know it will be done sometime before or after the value is returned. This also means that modifying a variable twice in the same statement will lead to undefined behaviour. Avoid statements like:
$i = $i ++;
print ++ $i + $i ++;
Perl will not guarantee what the result of the above statements is.

The "Whatever" Operator: ..

STRING .. STRING

Assigning the lowercase letters 'a' though 'z' to an array:
my @alphabet = ( 'a' .. 'z' );

Scalar::Util

use Scalar::Util 'blessed';
# or
use Scalar::Util 'looks_like_number';
#or both
use Scalar::Util qw(blessed looks_like_number);
my $is_number = looks_like_number('3fred'); # false
my $is_number = looks_like_number('3e7'); # true

Numeric Builtins

Arithmetic Operators: +, -, *, /, and **

NUMBER + NUMBER
NUMBER - NUMBER
NUMBER * NUMBER
NUMBER / NUMBER
NUMBER NUMBER**

The Modulus Operator: %

INTEGER % INTEGER

abs()

abs (defaults to $_)
abs NUMBER

exp()

exp (defaults to $_)
exp NUMBER

hex() and oct()

hex (defaults to $_)
hex STRING
oct (defaults to $_)
oct STRING

int()

int (defaults to $_)
int NUMBER

log()

log (defaults to $_)
log NUMBER

rand() and srand()

rand NUMBER
srand NUMBER

sprintf() and printf()

sprintf FORMAT, LIST
printf FILEHANDLE FORMAT, LIST
printf FORMAT, LIST

sqrt()

sqrt (defaults to $_)
sqrt NUMBER

Trigonometric Function: atan2(), cos(), and sin()

atan2 (defaults to $_)
atan2 NUMBER
cos (defaults to $_)
cos NUMBER
sin (defaults to $_)
sin NUMBER

Bitwise Operators

Understanding Booleans

eq, ne, lt, le, gt, ge, cpm

The following prints "yes":
if ( 'a' le 'bb ) {
print 'yes';
} else {
print 'no';
}

Boolean Numeric Operators

Logic Boolean Operators

Examples
if ( ! $value ) {
print "$value is false";
}
if ( $value1 && $value2 ) {
print "both values are true";
}
if ( $value1 || $value2 ) {
print "One or both of the values are true";
}
if ( $value1 // $value2 ) {
print "One or both of the values are defined";
}
if ( $value1 xor $value2 ) {
print "Either $value1 or $value2 is true, but not both";
}

my $zero = 0;
my $two = 2;
my $three = 3;
my $x = $zero && $two; # $x is 0
my $y = $three && $zero; # $y is 0
my $z = $two && $three; # $z is 3

my $ zero = 0;
my $two = 2;
my $three = 3;
my $undef;
my $w = $zero || $two; # $w is 2
my $x = $undef || $zero; # $x is 0
my $y = $zero // $two; # $y is 0
my $z = $undef // $three; # $z is 3

Assignment Operators

Precedence and Associativity

ARRAY AND LIST FUNCTIONS

Built-in Array Functions

pop() and push()

pop (defaults to @_)
pop ARRAY
push ARRAY, LIST

shift() and unshift()

shift (defaults to @_)
shift ARRAY
unshift ARRAY, LIST

splice()

splice ARRAY, OFFSET, LENGTH, LIST
splice ARRAY, OFFSET, LENGTH
splice ARRAY, OFFSET
splice ARRAY

my @writers = qw( Horace Ovid Virgil Asimov Heinlein Dante );
my @contemporary = splice @writers, 3, 2;

join() and split()

join STRING, LIST
split PATTERN, STRING
split PATTERN, STRING, LIMIT

reverse()

reverse LIST

my @array = ( 7, 8, 9 );
my @reversed = reverse @array; # ( 9, 8, 7 ) in @reversed
my $scalar = reverse @array; # 987 in $scalar
my $desserts = reverse 'stressed';
OR
my $desserts = scalar reverse 'stressed';

sort()

sort LIST

# sorting alphabetically
my @sorted = sort @array;
# sorting alphabetically in reverse order
my @sorted = sort { $b<=>$a } @array;
# sorting numerically
my @sorted = sort { $a<=>$b } @array;
# sorting numerically in reverse order
my @sorted = sort { $b<=>$a } @array;

grep()

grep EXPR, LIST
grep BLOCK, LIST

Get all values greater than 5:
my @list = grep { $_ > 5 } @array;
Remove all values less than 100:
@array = grep { $_ < 100 } @array;

map()

map EXPR, LIST
map BLOCK, LIST

Multiply every value in a list by 2:
my @doubled = map { $_ * 2 } @array;
Uppercase every element in a list:
my @upper = map { uc($_) } @array;
OR:
my @upper = map { uc } @array; # As the uc() function defaults to operate on $_
Take the square root of all values in a list that are greater than zero:
my @roots = map { sqrt } grep { $_ > 0 } @numbers; # Chaining map() and grep()
OR (more readable style):
my @roots = map { sqrt }

grep { $_ > 0 }
@numbers;

List::Util

Sum all elements in a list together:
use List::Util 'sum';
my $total = sum @numbers;
Because sum() accepts lists and not just a single array:
my $total = sum @weight_supplies, @weights_food;

BUILT-IN HASH FUNCTIONS

delete()

delete KEY

my %birth_year_for = (

Virgil => '70 BCE',
Shakespeare => '1564 CE',
'Elizabeth Barrett Browning' => '1806 CE',
'Carrot Top' => '1965 CE',
);
delete $birth_year_for{'Carrot Top'};

exists()

exists KEY

my %birth_year_for;
if ( exists $birth_year_for{'Carrot Top'} ) {

print "Carrot Top not expurgated!";
} else {
print "Carrot Top not found!";
}

keys()

keys HASH

for my $key (keys %hash) {
if ( $hash{$key} < 10 ) {
delete $hash{$key};
}
}

values()

values HASH

my @large_enough = grep { $_ >= 10 } values %hash;

each()

each HASH

while ( my ( $key, $value ) = each %hash ) {

print "$key: $value\n";
}

# this is always safe
for my $key (keys %hash) {
my $value= $hash{$key};
}

SCOPING KEYWORDS

my()

my VARIABLE
my (LIST OF VARIABLES)

local()

local VARIABLE
local (LIST OF VARIABLES)

our()

our VARIABLE
our (LIST OF VARIABLES)

state()

state VARIABLE

sub counter {
state $counter = 1;
print "This sub was called $counter times\n";
$counter++;
}
for (1..10) { counter() }



Backlinks: