scalar data types

31
Perl Programming Course Scalar data types Scalar data types Krasimir Berov I-can.eu

Upload: krasimir-berov

Post on 11-May-2015

1.897 views

Category:

Technology


0 download

DESCRIPTION

This is the second set of slightly updated slides from a Perl programming course that I held some years ago. I want to share it with everyone looking for intransitive Perl-knowledge. A table of content for all presentations can be found at i-can.eu. The source code for the examples and the presentations in ODP format are on https://github.com/kberov/PerlProgrammingCourse

TRANSCRIPT

Page 1: Scalar data types

Perl Programming Course

Scalar data typesScalar data types

Krasimir Berov

I-can.eu

Page 2: Scalar data types

Contents

1. Perl variables/data types

2. Numeric operators

3. String operators

4. Scalar functions (summary)

5. Undefined quantities

6. Type-casting in Perl?

7. References

Page 3: Scalar data types

Perl variable/data types

Perl has three main variable types: – scalars

– arrays

– hashes

... Plus two additional:– typeglobs

– filehandles

See: perlintro, perldata

Page 4: Scalar data types

Variable names

● Values are usually referred to by name, or through a named reference.

● The first character tells you to what sort/type of data structure it refers ($,@,%).

● The rest is the name of the particular value to which it refers.

● Usually this name is a single identifier – a string beginning with a letter or underscore, and containing letters, underscores, and digits.

● It may be also a chain of identifiers, separated by :: (see perlmod/Packages, perlref).

Page 5: Scalar data types

Perl Scalars

● A scalar can contain a single string (of any size, limited only by the available memory), number, or a reference to something (see perlref).

● There are also a number of "magic" scalars with names that look like punctuation or line noise ($_, $/, $] ...).

my $animal = "camel";my $animal = "camel";my $answer = 22;my $answer = 22;print "Me: Hello $animal! How old are you?\n";print "Me: Hello $animal! How old are you?\n";print "$animal: $answer.$/";print "$animal: $answer.$/";print '-'x 20, $/;print '-'x 20, $/;print 'Named reference: ',${animal},$/;print 'Named reference: ',${animal},$/;$Other::animal = 'llama';$Other::animal = 'llama';print "From package 'Other': $Other::animal\n";print "From package 'Other': $Other::animal\n";print 'Perl version: ',$], $/;print 'Perl version: ',$], $/;

Page 6: Scalar data types

Perl Arrays

● Arrays are ordered lists of scalars indexed by number, starting with 0.

my @animals = ("camel", "llama", "пиле");my @animals = ("camel", "llama", "пиле");my @numbers = (23, 42, 69);my @numbers = (23, 42, 69);my @mixed = ("camel", 42, 1.23);my @mixed = ("camel", 42, 1.23);print @animals .$/;#what the...;) scalar contextprint @animals .$/;#what the...;) scalar contextprint "@animals" . $/;#interpolated arrayprint "@animals" . $/;#interpolated arrayprint "@animals @numbers" . $/;#interpolated arraysprint "@animals @numbers" . $/;#interpolated arraysprint @animals, @numbers, $/;#list contextprint @animals, @numbers, $/;#list context

Page 7: Scalar data types

Perl Hashes

● Hashes are unordered collections of scalar values indexed by their associated string key.

my %fruit_colors = (my %fruit_colors = ( apple => "red",apple => "red", banana => "yellow",banana => "yellow",););print print map { "$_ => $fruit_colors{$_}\n" } map { "$_ => $fruit_colors{$_}\n" } sortsort keys %fruit_colors;keys %fruit_colors;print "%fruit_colors\n"; #hashes can NOT be interpolatedprint "%fruit_colors\n"; #hashes can NOT be interpolated

Page 8: Scalar data types

Back to Scalars?!..

Page 9: Scalar data types

Scalar values

● All data in Perl is a scalar, an array of scalars, or a hash of scalars.

● A scalar may contain one single value which is:– String

– Number

– Reference (more later)

– Filehandle (another time (I/O) )

● Conversion from one form to another is transparent

● Scalar values are by default undefined.

Page 10: Scalar data types

What are scalars (revisited)

● A scalar is a single string, number, or a reference to something.

● A scalar value is interpreted as TRUE in the Boolean sense if it is not the null string or the number 0 (or its string equivalent, "0").

#try this on the commandline#try this on the commandline>perl -e 'print "true\n" if "0" '>perl -e 'print "true\n" if "0" '>perl -e 'print "false\n" unless "0" '>perl -e 'print "false\n" unless "0" '>...>...

Page 11: Scalar data types

Scalar functions or operators?

● Many of the built-in functions in Perl are referred often to as named operators

● There are several categories depending on the usage, type of manipulated or produced data, etc.

● For example:– Functions for SCALARs or strings

– Numeric functions

– Regular expressions and pattern matching...● One function/operator may fall in one or more categories

depending on the context.

Page 12: Scalar data types

Assignment operator● The most common operation on a scalar (or

array, or hash) variable is assignment.● This way we give a value to a variable.● This way we give a name to a literal value.

my $name = 'Larry Wall';my $name = 'Larry Wall';print 'My name is ', $name, $/;print 'My name is ', $name, $/;

Page 13: Scalar data types

Numeric operators

● Named operators (functions) that act on numbers and produce numbers– abs, hex, oct

Page 14: Scalar data types

Numeric operators

● abs VALUEabsReturns the absolute value of its argument. If VALUE is omitted, uses $_.

● See perlfunc/abs

my $answer = -22;my $answer = -22;print abs $answer;print abs $answer;print abs "$answer";print abs "$answer";

Page 15: Scalar data types

Numeric operators

● hex EXPRhex Interprets EXPR as a hex string and returns the decimal value. (To convert strings that might start with either 0, 0x, or 0b, see oct.) If EXPR is omitted, uses $_.

● To present something as hex, look into printf, sprintf, or unpack.

● See perlfunc/hex

print hex '0xBf';print hex '0xBf';print hex 'bF';print hex 'bF';

Page 16: Scalar data types

Numeric operators

● oct EXPRoct Interprets EXPR as an octal string and returns the corresponding value.

– If EXPR starts off with 0x, interprets it as a hex string. If EXPR starts off with 0x, interprets it as a hex string. – If EXPR starts off with 0b, it is interpreted as a binary If EXPR starts off with 0b, it is interpreted as a binary

string. string. – Leading whitespace is ignored in all three cases.Leading whitespace is ignored in all three cases.– If EXPR is omitted, uses $_. If EXPR is omitted, uses $_. – To go the other way (produce a number in octal), use To go the other way (produce a number in octal), use

sprintf() or printf()sprintf() or printf()print( oct 0b10, $/);print( oct 0b10, $/);print( oct '0xBf', $/);print( oct '0xBf', $/);print( oct '07', $/);print( oct '07', $/);print( oct '0777', $/);print( oct '0777', $/);

Page 17: Scalar data types

String operators

● Named operators (functions) for SCALARs or strings– length, chop and chomp, uc/lc

Page 18: Scalar data types

String operators

● length EXPRlengthReturns the length in characters of the value of EXPR.

– If EXPR is omitted, returns length of $_. If EXPR is omitted, returns length of $_. – Cannot be used on an array or hash to find out how Cannot be used on an array or hash to find out how

many elements these have. many elements these have. – For that, use For that, use scalar @arrayscalar @array and and scalar keys %hashscalar keys %hash

respectively.respectively.– if the EXPR is in Unicode, you will get the number of if the EXPR is in Unicode, you will get the number of

characters, not the number of bytescharacters, not the number of bytesuse utf8;use utf8;print( length 'kniga' , $/);print( length 'kniga' , $/);use bytes;use bytes;print( length 'книга', $/);print( length 'книга', $/);no bytes;no bytes;print( length 'книга', $/);print( length 'книга', $/);

Page 19: Scalar data types

String operators

● chop VARIABLEchop( LIST )chopChops off the last character of a string and returns the character chopped.

– If VARIABLE is omitted, chops $_. If VARIABLE is omitted, chops $_. – If VARIABLE is a hash, it chops the hash's values, but If VARIABLE is a hash, it chops the hash's values, but

not its keys.not its keys.– If you chop a list, each element is chopped. Only the If you chop a list, each element is chopped. Only the

value of the last chop is returned.value of the last chop is returned.#!/usr/bin/perl -C#!/usr/bin/perl -C#binmode(STDOUT, ':encoding(cp866)');#on win32#binmode(STDOUT, ':encoding(cp866)');#on win32use utf8; use utf8; binmode(STDOUT, ':utf8');binmode(STDOUT, ':utf8');my ($bob_latin, $bob_cyr) = ('bob', 'боб');my ($bob_latin, $bob_cyr) = ('bob', 'боб');print( chop($bob_latin) , $/, chop($bob_cyr) , $/);print( chop($bob_latin) , $/, chop($bob_cyr) , $/);

Page 20: Scalar data types

String operators

● chomp VARIABLEchomp( LIST )chompSafer version of chop.

– Removes any trailing string that corresponds to the Removes any trailing string that corresponds to the current value of $/.current value of $/.

– Returns the total number of characters removed Returns the total number of characters removed from all its arguments.from all its arguments.

#binmode(STDOUT, ':encoding(cp866)');#on win32#binmode(STDOUT, ':encoding(cp866)');#on win32use utf8; use utf8; binmode(STDOUT, ':utf8');binmode(STDOUT, ':utf8');my ($bob_latin, $bob_cyr) = ("bob\n", "боб$/");my ($bob_latin, $bob_cyr) = ("bob\n", "боб$/");print( $bob_latin, $bob_cyr, $/ );print( $bob_latin, $bob_cyr, $/ );print( chomp($bob_latin,$bob_cyr) , $/ );print( chomp($bob_latin,$bob_cyr) , $/ );print( $bob_latin, $bob_cyr, $/ );print( $bob_latin, $bob_cyr, $/ );

Page 21: Scalar data types

String operators

● lc EXPRlcReturns a lowercased version of EXPR. If EXPR is omitted, uses $_.

● uc EXPRucReturns an uppercased version of EXPR. If EXPR is omitted, uses $_.

#binmode(STDOUT, ':encoding(cp866)');#on win32#binmode(STDOUT, ':encoding(cp866)');#on win32use utf8; use utf8; binmode(STDOUT, ':utf8');binmode(STDOUT, ':utf8');my ($lcstr, $ucstr) = ("BOB\n", "боб$/");my ($lcstr, $ucstr) = ("BOB\n", "боб$/");print( lc $lcstr, uc($ucstr), $/ );print( lc $lcstr, uc($ucstr), $/ );

Page 22: Scalar data types

Un/defined quantities

● undef => nothing, empty, void● defined => something not undef :)

Page 23: Scalar data types

Un/defined quantities

● undef EXPRundefUndefines the value of EXPR, which must be an lvalue.

– Use only on a scalar value, an array (using @), a hash (using %), a subroutine (using &), or a typeglob (using *)...

– Always returns the undefined value.

#use strict; use warnings; use diagnostics;#use strict; use warnings; use diagnostics;my $name;my $name;print $name ,$/;print $name ,$/;$name ="Larry";$name ="Larry";print $name ,$/;print $name ,$/;undef $name ;undef $name ;print $name ,$/;print $name ,$/;

Page 24: Scalar data types

Un/defined quantities

● defined EXPRdefinedReturns a Boolean value telling whether EXPR has a value other than the undefined value undef.

– If EXPR is not present, $_ will be checked.If EXPR is not present, $_ will be checked.

– Allows you to distinguish undef from other values. Allows you to distinguish undef from other values.

– A simple Boolean test will not distinguish among undef, A simple Boolean test will not distinguish among undef, zero, the empty string, and "0", which are all equally zero, the empty string, and "0", which are all equally false.false.my $data;my $data;

print $data if defined($data);print $data if defined($data);$data = 0;$data = 0;print defined($data);print defined($data);print $data if defined($data);print $data if defined($data);undef $data;undef $data;print defined($data);print defined($data);$_ = 2;$_ = 2;print defined;print defined;

Page 25: Scalar data types

Scalar functions (summary)

● Functions for SCALARs or strings– chomp, chop, chr, crypt, hex, index, lc, lcfirst,

length, oct, ord, pack, q//, qq//, reverse, rindex, sprintf, substr, tr///, uc, ucfirst, y///

● Numeric functions– abs, atan2, cos, exp, hex, int, log, oct, rand, sin,

sqrt, srand

● Miscellaneous functions● defined, dump, eval, formline, local, my, our, reset,

scalar, undef, wantarray

● See perlfunc

Page 26: Scalar data types

Type casting operations :X :(● C Operators Missing From Perl:

– Type-casting operator

– ...

● From perlglossary:– type casting: Converting data from one type to

another. C permits this. Perl does not need it. Nor want it.

● I hope you have in mind references :)...

Page 27: Scalar data types

References● A scallar can also contain a reference.

● A reference is just a piece of data pointing to another piece of data (anonimous or named).

● In Perl, a reference is always a scalar, although the data it refers to may not be

● Languages like C and C++ have a feature that's similar to references, called pointers.

● Pointers leave interpretation of what's there for the programmer

● References only store memory locations for specific, clearly defined data structures – maybe not predefined, but defined nevertheless.

● References allow you to leave the arrangement of computer memory to the computer itself.

Page 28: Scalar data types

References● ref EXPR

refReturns a non-empty string if EXPR is a reference, the empty string otherwise.

– If EXPR is not specified, $_ will be used. If EXPR is not specified, $_ will be used. – The value returned depends on the type of thing the The value returned depends on the type of thing the

reference is a reference to. reference is a reference to. – Builtin types include:Builtin types include:

SCALAR, ARRAY, HASH, CODE, REF, GLOB, LVALUE, SCALAR, ARRAY, HASH, CODE, REF, GLOB, LVALUE, FORMAT, IO, RegexpFORMAT, IO, Regexp

– If the referenced object has been If the referenced object has been blessblessed into a ed into a package, then that package name is returned instead.package, then that package name is returned instead.

– You can think of You can think of refref as a typeof operator. as a typeof operator.

Page 29: Scalar data types

References● Example

● References will be discussed another time

use Data::Dumper; use Data::Dumper; my %hash = (me =>'you' );my %hash = (me =>'you' );my @array = ('we',\%hash,['them']);my @array = ('we',\%hash,['them']);my $scalar = \@array;my $scalar = \@array;print ref $scalar, $/;print ref $scalar, $/;print $scalar,$/;print $scalar,$/;print Dumper($scalar);print Dumper($scalar);

Page 30: Scalar data types

Scalar data types

Questions?

Page 31: Scalar data types

Exercises1. Write a program that converts a given hex digit to decimal

and displays it on the screen.

2. Write a program which displays the absolute of a negative number.

3. Write a program which removes the last letter from a string (no matter what the string is) and displays the letter on the screen.

4. Write a program which converts a number to its corresponding character and displays the letter on the screen.

5. Write a program which prints the string 'Здрасти' 3 times on 3 separate lines using only one print statement.