pairs unpairs pairkeys pairvalues pairfirst pairgrep pairmap

Size: px
Start display at page:

Download "pairs unpairs pairkeys pairvalues pairfirst pairgrep pairmap"

Transcription

1 NAME SYNOPSIS List::Util - A selection of general-utility list subroutines use List::Util qw( reduce any all none notall first max maxstr min minstr product sum sum0 pairs unpairs pairkeys pairvalues pairfirst pairgrep pairmap DESCRIPTION shuffle uniq uniqnum uniqstr ); List::Util contains a selection of subroutines that people have expressed would be nice to have in the perl core, but the usage would not really be high enough to warrant the use of a keyword, and the size so small such that being individual extensions would be wasteful. By default List::Util does not export any subroutines. LIST-REDUCTION FUNCTIONS reduce The following set of functions all reduce a list down to a single value. $result = reduce { by calling BLOCK in a scalar context multiple times, setting $a and $b each time. The first call will be with $a and $b set to the first two elements of the list, subsequent calls will be done by setting $a to the result of the previous call and $b to the next element in the list. Returns the result of the last call to the BLOCK. is empty then undef is returned. only contains one element then that element is returned and BLOCK is not executed. The following examples all demonstrate how reduce could be used to implement the other list-reduction functions in this module. (They are not in fact implemented like this, but instead in a more efficient manner in individual C functions). $foo = reduce { defined($a)? $a : $code->(local $_ = $b)? $b : undef # first $foo = reduce { $a > $b? $a : $b # max $foo = reduce { $a gt $b? $a : $b 'A'..'Z' # maxstr $foo = reduce { $a < $b? $a : $b # min $foo = reduce { $a lt $b? $a : $b 'aa'..'zz' # minstr $foo = reduce { $a + $b # sum $foo = reduce { $a. # concat $foo = reduce { $a $code->(local $_ = $b) # any $foo = reduce { $a && $code->(local $_ = $b) # all $foo = reduce { $a &&!$code->(local $_ = $b) # none $foo = reduce { $a!$code->(local $_ = $b) # notall # Note that these implementations do not fully short-circuit Page 1

2 If your algorithm requires that reduce produce an identity value, then make sure that you always pass that identity value as the first argument to prevent undef being returned $foo = reduce { $a + $b value # sum with 0 identity The above example code blocks also suggest how to use reduce to build a more efficient combined version of one of these basic functions and a map block. For example, to find the total length of the all the strings in a list, we could use $total = sum map { However, this produces a list of temporary integer values as long as the original list of strings, only to reduce it down to a single value again. We can compute the same result more efficiently by using reduce with a code block that accumulates lengths by writing this instead as: $total = reduce { $a + length $b The remaining list-reduction functions are all specialisations of this generic idea. any my $bool = any { Since version Similar to grep in that it evaluates BLOCK setting $_ to each element in turn. any returns true if any element makes the BLOCK return a true value. If BLOCK never returns true was empty then it returns false. Many cases of using grep in a conditional can be written using any instead, as it can short-circuit after the first true result. if( any { length > ) { # at least one string has more than 10 characters all my $bool = all { Since version Similar to any, except that it requires all elements of to make the BLOCK return true. If any element returns false, then it returns false. If the BLOCK never returns false or was empty then it returns true. none notall my $bool = none { my $bool = notall { Since version Similar to any and all, but with the return sense inverted. none returns true only if no value in causes the BLOCK to return true, and notall returns true only if not all of the values do. Page 2

3 first my $val = first { Similar to grep in that it evaluates BLOCK setting $_ to each element in turn. first returns the first element where the result from BLOCK is a true value. If BLOCK never returns true was empty then undef is returned. $foo = first { $foo = first { $_ > # first defined value # first value which # is greater than $value max my $num = Returns the entry in the list with the highest numerical value. If the list is empty then undef is returned. $foo = max # 10 $foo = max 3,9,12 # 12 $foo maxstr my $str = Similar to max, but treats all the entries in the list as strings and returns the highest string as defined by the gt operator. If the list is empty then undef is returned. $foo = maxstr 'A'..'Z' $foo = maxstr "hello","world" $foo # 'Z' # "world" min my $num = Similar to max but returns the entry in the list with the lowest numerical value. If the list is empty then undef is returned. $foo = min # 1 $foo = min 3,9,12 # 3 $foo minstr my $str = Similar to min, but treats all the entries in the list as strings and returns the lowest string as defined by the lt operator. If the list is empty then undef is returned. $foo = minstr 'A'..'Z' $foo = minstr "hello","world" $foo # 'A' # "hello" Page 3

4 product my $num = Since version Returns the numerical product of all the elements is empty then 1 is returned. $foo = product # $foo = product 3,9,12 # 324 sum my $num_or_undef = Returns the numerical sum of all the elements For backwards compatibility, is empty then undef is returned. $foo = sum # 55 $foo = sum 3,9,12 # 24 $foo sum0 my $num = Since version Similar to sum, except this returns 0 when given an empty list, rather than undef. KEY/VALUE PAIR LIST FUNCTIONS The following set of functions, all inspired by List::Pairwise, consume an even-sized list of pairs. The pairs may be key/value associations from a hash, or just a list of values. The functions will all preserve the original ordering of the pairs, and will not be confused by multiple pairs having the same "key" value - nor even do they require that the first of each pair be a plain string. NOTE: At the time of writing, the following pair* functions that take a block do not modify the value of $_ within the block, and instead operate using the $a and $b globals instead. This has turned out to be a poor design, as it precludes the ability to provide a pairsort function. Better would be to pass pair-like objects as 2-element array references in $_, in a style similar to the return value of the pairs function. At some future version this behaviour may be added. Until then, users are alerted NOT to rely on the value of $_ remaining unmodified between the outside and the inside of the control block. In particular, the following example is UNSAFE: =... foreach (qw( some keys here )) { = pairgrep { $a eq Instead, write this using a lexical variable: foreach my $key (qw( some keys here )) { = pairgrep { $a eq Page 4

5 pairs = A convenient shortcut to operating on even-sized lists of pairs, this function returns a list of ARRAY references, each containing two items from the given list. It is a more efficient version = pairmap { [ $a, $b It is most convenient to use in a foreach loop, for example: foreach my $pair ( ) { my ( $key, $value ) Since version 1.39 these ARRAY references are blessed objects, recognising the two methods key and value. The following code is equivalent: foreach my $pair ( ) { my $key = $pair->key; my $value = $pair->value;... unpairs = Since version The inverse function to pairs; this function takes a list of ARRAY references containing two elements each, and returns a flattened list of the two values from each of the pairs, in order. This is notionally equivalent to = except that it is implemented more efficiently internally. Specifically, for any input item it will extract exactly two values for the output list; using undef if the input array references are short. Between pairs and unpairs, a higher-order list function can be used to operate on the pairs as single scalars; such as the following near-equivalents of the other pair* higher-order = unpairs grep { FUNC # Like pairgrep, but takes $_ instead of $a and = unpairs map { FUNC # Like pairmap, but takes $_ instead of $a and $b Note however that these versions will not behave as nicely in scalar context. Finally, this technique can be used to implement a sort on a keyvalue pair list; = unpairs sort { $a->key cmp $b->key Page 5

6 pairkeys = A convenient shortcut to operating on even-sized lists of pairs, this function returns a list of the the first values of each of the pairs in the given list. It is a more efficient version = pairmap { pairvalues = A convenient shortcut to operating on even-sized lists of pairs, this function returns a list of the the second values of each of the pairs in the given list. It is a more efficient version = pairmap { pairgrep = pairgrep { my $count = pairgrep { Similar to perl's grep keyword, but interprets the given list as an even-sized list of pairs. It invokes the BLOCK multiple times, in scalar context, with $a and $b set to successive pairs of values from Returns an even-sized list of those pairs for which the BLOCK returned true in list context, or the count of the number of pairs in scalar context. (Note, therefore, in scalar context that it returns a number half the size of the count of items it would have returned in list = pairgrep { $a =~ As with grep aliasing $_ to list elements, pairgrep aliases $a and $b to elements of the given list. Any modifications of it by the code block will be visible to the caller. pairfirst my ( $key, $val ) = pairfirst { my $found = pairfirst { Since version Similar to the first function, but interprets the given list as an even-sized list of pairs. It invokes the BLOCK multiple times, in scalar context, with $a and $b set to successive pairs of values from Returns the first pair of values from the list for which the BLOCK returned true in list context, or an empty list of no such pair was found. In scalar context it returns a simple boolean value, rather than either the key or the value found. Page 6

7 ( $key, $value ) = pairfirst { $a =~ As with grep aliasing $_ to list elements, pairfirst aliases $a and $b to elements of the given list. Any modifications of it by the code block will be visible to the caller. pairmap = pairmap { my $count = pairmap { Similar to perl's map keyword, but interprets the given list as an even-sized list of pairs. It invokes the BLOCK multiple times, in list context, with $a and $b set to successive pairs of values from Returns the concatenation of all the values returned by the BLOCK in list context, or the count of the number of items that would have been returned in scalar = pairmap { "The key $a has value As with map aliasing $_ to list elements, pairmap aliases $a and $b to elements of the given list. Any modifications of it by the code block will be visible to the caller. See KNOWN BUGS for a known-bug with pairmap, and a workaround. OTHER FUNCTIONS shuffle = Returns the values of the input in a random = shuffle # in a random order uniq = Since version Filters a list of values to remove subsequent duplicates, as judged by a DWIM-ish string equality or undef test. Preserves the order of unique elements, and retains the first value of any duplicate set. my $count = In scalar context, returns the number of elements that would have been returned as a list. The undef value is treated by this function as distinct from the empty string, and no warning will be produced. It is left as-is in the returned list. Subsequent undef values are still considered identical to the first, and will be removed. uniqnum = Since version Page 7

8 Filters a list of values to remove subsequent duplicates, as judged by a numerical equality test. Preserves the order of unique elements, and retains the first value of any duplicate set. my $count = In scalar context, returns the number of elements that would have been returned as a list. Note that undef is treated much as other numerical operations treat it; it compares equal to zero but additionally produces a warning if such warnings are enabled (use warnings 'uninitialized'; ). In addition, an undef in the returned list is coerced into a numerical zero, so that the entire list of values returned by uniqnum are well-behaved as numbers. Note also that multiple IEEE NaN values are treated as duplicates of each other, regardless of any differences in their payloads, and despite the fact that 0+'NaN' == 0+'NaN' yields false. uniqstr = Since version Filters a list of values to remove subsequent duplicates, as judged by a string equality test. Preserves the order of unique elements, and retains the first value of any duplicate set. my $count = KNOWN BUGS RT #95409 In scalar context, returns the number of elements that would have been returned as a list. Note that undef is treated much as other string operations treat it; it compares equal to the empty string but additionally produces a warning if such warnings are enabled (use warnings 'uninitialized';). In addition, an undef in the returned list is coerced into an empty string, so that the entire list of values returned by uniqstr are well-behaved as strings. If the block of code given to pairmap contains lexical variables that are captured by a returned closure, and the closure is executed after the block has been re-used for the next iteration, these lexicals will not see the correct values. For example: = pairmap { my $var = "$a is $b"; sub { print "$var\n" ; one => 1, two => 2, three => 3; $_->() Will incorrectly print three is 3 three is 3 three is 3 This is due to the performance optimisation of using MULTICALL for the code block, which means that fresh SVs do not get allocated for each call to the block. Instead, the same SV is re-assigned for each iteration, and all the closures will share the value seen on the final iteration. Page 8

9 To work around this bug, surround the code with a second set of braces. This creates an inner block that defeats the MULTICALL logic, and does get fresh SVs allocated each time: = pairmap { { my $var = "$a is $b"; sub { print "$var\n"; one => 1, two => 2, three => 3; This bug only affects closures that are generated by the block but used afterwards. Lexical variables that are only used during the lifetime of the block's execution will take their individual values for each invocation, as normal. uniqnum() on oversized bignums Due to the way that uniqnum() compares numbers, it cannot distinguish differences between bignums (especially bigints) that are too large to fit in the native platform types. For example, my $x = Math::BigInt->new( "1" x 100 ); my $y = $x + 1; say for uniqnum( $x, $y ); Will print just the value of $x, believing that $y is a numerically- equivalent value. This bug does not affect uniqstr(), which will correctly observe that the two values stringify to different strings. SUGGESTED ADDITIONS The following are additions that have been requested, but I have been reluctant to add due to them being very simple to implement in perl # How many elements are true sub true { scalar grep { # How many elements are false SEE ALSO COPYRIGHT sub false { scalar grep Scalar::Util, List::MoreUtils Copyright (c) Graham Barr <gbarr@pobox.com>. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. Recent additions and current maintenance by Paul Evans, <leonerd@leonerd.org.uk>. Page 9

A control expression must evaluate to a value that can be interpreted as true or false.

A control expression must evaluate to a value that can be interpreted as true or false. Control Statements Control Expressions A control expression must evaluate to a value that can be interpreted as true or false. How a control statement behaves depends on the value of its control expression.

More information

lock_ref_keys unlock_ref_keys lock_ref_value unlock_ref_value lock_hashref unlock_hashref lock_ref_keys_plus hidden_ref_keys legal_ref_keys

lock_ref_keys unlock_ref_keys lock_ref_value unlock_ref_value lock_hashref unlock_hashref lock_ref_keys_plus hidden_ref_keys legal_ref_keys NAME Hash::Util - A selection of general-utility hash subroutines SYNOPSIS # Restricted hashes use Hash::Util qw( fieldhash fieldhashes all_keys lock_keys unlock_keys lock_value unlock_value lock_hash

More information

Data::Dumper - stringified perl data structures, suitable for both printing and eval

Data::Dumper - stringified perl data structures, suitable for both printing and eval NAME SYNOPSIS Data::Dumper - stringified perl data structures, suitable for both printing and eval use Data::Dumper; # simple procedural interface print Dumper($foo, $bar); # extended usage with names

More information

CS 105 Perl: Completing the Toolbox

CS 105 Perl: Completing the Toolbox CS 105 Perl: Completing the Toolbox March 4, 2013 Agenda autodie with open Inspecting scalars perl -c Unary coercion Topicalization ~~ Unique list idiom Schwartzian Transform Using // for defaults and

More information

Data::Dumper - stringified perl data structures, suitable for both printing and eval

Data::Dumper - stringified perl data structures, suitable for both printing and eval NAME SYNOPSIS Data::Dumper - stringified perl data structures, suitable for both printing and eval use Data::Dumper; # simple procedural interface print Dumper($foo, $bar); # extended usage with names

More information

lock_ref_keys unlock_ref_keys lock_ref_value unlock_ref_value lock_hashref unlock_hashref lock_ref_keys_plus hidden_ref_keys legal_ref_keys

lock_ref_keys unlock_ref_keys lock_ref_value unlock_ref_value lock_hashref unlock_hashref lock_ref_keys_plus hidden_ref_keys legal_ref_keys NAME Hash::Util - A selection of general-utility hash subroutines SYNOPSIS # Restricted hashes use Hash::Util qw( fieldhash fieldhashes all_keys lock_keys unlock_keys lock_value unlock_value lock_hash

More information

CS 105 Perl: Perl subroutines and Disciplined Perl

CS 105 Perl: Perl subroutines and Disciplined Perl CS 105 Perl: Perl subroutines and Disciplined Perl Nathan Clement! February 3, 2014 Agenda We will cover Perl scoping, subroutines (user- defined functions) and then we continue on to Perl s features for

More information

Pathologically Eclectic Rubbish Lister

Pathologically Eclectic Rubbish Lister Pathologically Eclectic Rubbish Lister 1 Perl Design Philosophy Author: Reuben Francis Cornel perl is an acronym for Practical Extraction and Report Language. But I guess the title is a rough translation

More information

1. Introduction. 2. Scalar Data

1. Introduction. 2. Scalar Data 1. Introduction What Does Perl Stand For? Why Did Larry Create Perl? Why Didn t Larry Just Use Some Other Language? Is Perl Easy or Hard? How Did Perl Get to Be So Popular? What s Happening with Perl Now?

More information

package YourModule; require = = qw(munge frobnicate); # symbols to export on request

package YourModule; require = = qw(munge frobnicate); # symbols to export on request NAME SYNOPSIS Exporter - Implements default import method for modules In module YourModule.pm: require Exporter; @EXPORT_OK = qw(munge frobnicate); # symbols to export on request or use Exporter 'import';

More information

my $reply = $term->get_reply( prompt => 'What is your favourite colour?', choices => [qw blue red green ], default => blue, );

my $reply = $term->get_reply( prompt => 'What is your favourite colour?', choices => [qw blue red green ], default => blue, ); NAME SYNOPSIS Term::UI - Term::ReadLine UI made easy use Term::UI; use Term::ReadLine; my $term = Term::ReadLine->new('brand'); my prompt => 'What is your favourite colour?', choices => [qw blue red green

More information

Control Structures. Important Semantic Difference

Control Structures. Important Semantic Difference Control Structures Important Semantic Difference In all of these loops we are going to discuss, the braces are ALWAYS REQUIRED. Even if your loop/block only has one statement, you must include the braces.

More information

print inf + 42,"\n"; print NaN * 7,"\n"; print hex("0x "),"\n"; # Perl v or later

print inf + 42,\n; print NaN * 7,\n; print hex(0x ),\n; # Perl v or later NAME bigint - Transparent BigInteger support for Perl SYNOPSIS use bigint; $x = 2 + 4.5,"\n"; # BigInt 6 print 2 ** 512,"\n"; # really is what you think it is print inf + 42,"\n"; # inf print NaN * 7,"\n";

More information

Scripting Languages Perl Basics. Course: Hebrew University

Scripting Languages Perl Basics. Course: Hebrew University Scripting Languages Perl Basics Course: 67557 Hebrew University אליוט יפה Jaffe Lecturer: Elliot FMTEYEWTK Far More Than Everything You've Ever Wanted to Know Perl Pathologically Eclectic Rubbish Lister

More information

Subroutines. Subroutines. The Basics. aka: user-defined functions, methods, procdures, sub-procedures, etc etc etc.

Subroutines. Subroutines. The Basics. aka: user-defined functions, methods, procdures, sub-procedures, etc etc etc. Subroutines Subroutines aka: user-defined functions, methods, procdures, sub-procedures, etc etc etc We ll just say Subroutines. "Functions" generally means built-in functions perldoc perlsub The Basics

More information

use Params::Check qw[check allow last_error];

use Params::Check qw[check allow last_error]; NAME SYNOPSIS Params::Check - A generic input parsing/checking mechanism. use Params::Check qw[check allow last_error]; sub fill_personal_info { my %hash = @_; my $x; my $tmpl = { firstname => { required

More information

Calculations. 4.1 Check if a number is a prime

Calculations. 4.1 Check if a number is a prime 4 Calculations In this chapter, we ll look at various one-liners for performing calculations, such as finding minimum and maximum elements, counting, shuffling and permuting words, and calculating dates

More information

$bool = $obj->mk_aliases( # create an alias to an existing alias_name => 'method'); # method name

$bool = $obj->mk_aliases( # create an alias to an existing alias_name => 'method'); # method name NAME SYNOPSIS Object::Accessor - interface to create per object accessors ### using the object $obj = Object::Accessor->new; # create object $obj = Object::Accessor->new(@list); # create object with accessors

More information

1 Lexical Considerations

1 Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler

More information

Perl. Perl. Perl. Which Perl

Perl. Perl. Perl. Which Perl Perl Perl Perl = Practical Extraction and Report Language Developed by Larry Wall (late 80 s) as a replacement for awk. Has grown to become a replacement for awk, sed, grep, other filters, shell scripts,

More information

@EXPORT_OK = qw(munge frobnicate); # symbols to export on request

@EXPORT_OK = qw(munge frobnicate); # symbols to export on request NAME Exporter - Implements default import method for modules SYNOPSIS In module YourModule.pm: package YourModule; require Exporter; @ISA = qw(exporter); @EXPORT_OK = qw(munge frobnicate); # symbols to

More information

Tieing and Overloading Objects in Perl. Dave Cross Magnum Solutions

Tieing and Overloading Objects in Perl. Dave Cross Magnum Solutions Tieing and Overloading Objects in Perl Dave Cross Magnum Solutions What We Will Cover Why tie or overload? What We Will Cover Why tie or overload? Tieing objects What We Will Cover Why tie or overload?

More information

Examples of Using the ARGV Array. Loop Control Operators. Next Operator. Last Operator. Perl has three loop control operators.

Examples of Using the ARGV Array. Loop Control Operators. Next Operator. Last Operator. Perl has three loop control operators. Examples of Using the ARGV Array # mimics the Unix echo utility foreach (@ARGV) { print $_ ; print \n ; # count the number of command line arguments $i = 0; foreach (@ARGV) { $i++; print The number of

More information

IT441. Subroutines. (a.k.a., Functions, Methods, etc.) DRAFT. Network Services Administration

IT441. Subroutines. (a.k.a., Functions, Methods, etc.) DRAFT. Network Services Administration IT441 Network Services Administration Subroutines DRAFT (a.k.a., Functions, Methods, etc.) Organizing Code We have recently discussed the topic of organizing data (i.e., arrays and hashes) in order to

More information

$pat = '(?{ $foo = 1 })'; use re 'eval'; /foo${pat}bar/; # won't fail (when not under -T # switch)

$pat = '(?{ $foo = 1 })'; use re 'eval'; /foo${pat}bar/; # won't fail (when not under -T # switch) NAME SYNOPSIS re - Perl pragma to alter regular expression behaviour use re 'taint'; ($x) = ($^X =~ /^(.*)$/s); # $x is tainted here $pat = '(?{ $foo = 1 })'; use re 'eval'; /foo${pat}bar/; # won't fail

More information

my $full_path = can_run('wget') or warn 'wget is not installed!';

my $full_path = can_run('wget') or warn 'wget is not installed!'; NAME IPC::Cmd - finding and running system commands made easy SYNOPSIS use IPC::Cmd qw[can_run run run_forked]; my $full_path = can_run('wget') or warn 'wget is not installed!'; ### commands can be arrayrefs

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2010 Handout Decaf Language Tuesday, Feb 2 The project for the course is to write a compiler

More information

Perl. Many of these conflict with design principles of languages for teaching.

Perl. Many of these conflict with design principles of languages for teaching. Perl Perl = Practical Extraction and Report Language Developed by Larry Wall (late 80 s) as a replacement for awk. Has grown to become a replacement for awk, sed, grep, other filters, shell scripts, C

More information

The Power of Perl. Perl. Perl. Change all gopher to World Wide Web in a single command

The Power of Perl. Perl. Perl. Change all gopher to World Wide Web in a single command The Power of Perl Perl Change all gopher to World Wide Web in a single command perl -e s/gopher/world Wide Web/gi -p -i.bak *.html Perl can be used as a command Or like an interpreter UVic SEng 265 Daniel

More information

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1) Technology & Information Management Instructor: Michael Kremer, Ph.D. Class 2 Professional Program: Data Administration and Management JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1) AGENDA

More information

Now applying :unique to lexical variables and to subroutines will result in a compilation error.

Now applying :unique to lexical variables and to subroutines will result in a compilation error. NAME DESCRIPTION perl591delta - what is new for perl v5.9.1 This document describes differences between the 5.9.0 and the 5.9.1 development releases. See perl590delta for the differences between 5.8.0

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Fall 2005 Handout 6 Decaf Language Wednesday, September 7 The project for the course is to write a

More information

Scala : an LLVM-targeted Scala compiler

Scala : an LLVM-targeted Scala compiler Scala : an LLVM-targeted Scala compiler Da Liu, UNI: dl2997 Contents 1 Background 1 2 Introduction 1 3 Project Design 1 4 Language Prototype Features 2 4.1 Language Features........................................

More information

perl -MO=Deparse[,-d][,-fFILE][,-p][,-q][,-l] [,-sletters][,-xlevel] prog.pl

perl -MO=Deparse[,-d][,-fFILE][,-p][,-q][,-l] [,-sletters][,-xlevel] prog.pl NAME SYNOPSIS DESCRIPTION OPTIONS B::Deparse - Perl compiler backend to produce perl code perl -MO=Deparse[,-d][,-fFILE][,-p][,-q][,-l] [,-sletters][,-xlevel] prog.pl B::Deparse is a backend module for

More information

By default, optional warnings are disabled, so any legacy code that doesn't attempt to control the warnings will work unchanged.

By default, optional warnings are disabled, so any legacy code that doesn't attempt to control the warnings will work unchanged. SYNOPSIS use warnings; no warnings; use warnings "all"; no warnings "all"; use warnings::register; if (warnings::enabled()) warnings::warn("some warning"); if (warnings::enabled("void")) warnings::warn("void",

More information

COMP-520 GoLite Tutorial

COMP-520 GoLite Tutorial COMP-520 GoLite Tutorial Alexander Krolik Sable Lab McGill University Winter 2019 Plan Target languages Language constructs, emphasis on special cases General execution semantics Declarations Types Statements

More information

Indian Institute of Technology Kharagpur. PERL Part II. Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. I.I.T.

Indian Institute of Technology Kharagpur. PERL Part II. Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. I.I.T. Indian Institute of Technology Kharagpur PERL Part II Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. I.I.T. Kharagpur, INDIA Lecture 22: PERL Part II On completion, the student will be able

More information

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

COMS 3101 Programming Languages: Perl. Lecture 2

COMS 3101 Programming Languages: Perl. Lecture 2 COMS 3101 Programming Languages: Perl Lecture 2 Fall 2013 Instructor: Ilia Vovsha http://www.cs.columbia.edu/~vovsha/coms3101/perl Lecture Outline Control Flow (continued) Input / Output Subroutines Concepts:

More information

Project 3 Due October 21, 2015, 11:59:59pm

Project 3 Due October 21, 2015, 11:59:59pm Project 3 Due October 21, 2015, 11:59:59pm 1 Introduction In this project, you will implement RubeVM, a virtual machine for a simple bytecode language. Later in the semester, you will compile Rube (a simplified

More information

my $full_path = can_run('wget') or warn 'wget is not installed!';

my $full_path = can_run('wget') or warn 'wget is not installed!'; NAME IPC::Cmd - finding and running system commands made easy SYNOPSIS use IPC::Cmd qw[can_run run]; my $full_path = can_run('wget') or warn 'wget is not installed!'; ### commands can be arrayrefs or strings

More information

Programming Languages Third Edition. Chapter 10 Control II Procedures and Environments

Programming Languages Third Edition. Chapter 10 Control II Procedures and Environments Programming Languages Third Edition Chapter 10 Control II Procedures and Environments Objectives Understand the nature of procedure definition and activation Understand procedure semantics Learn parameter-passing

More information

Hash::Util::FieldHash offers a number of functions in support of The Inside-out Technique of class construction.

Hash::Util::FieldHash offers a number of functions in support of The Inside-out Technique of class construction. NAME SYNOPSIS Hash::Util::FieldHash - Support for Inside-Out Classes ### Create fieldhashes use Hash::Util qw(fieldhash fieldhashes); # Create a single field hash fieldhash my %foo; # Create three at once...

More information

use attributes (); # optional, to get subroutine declarations = attributes::get(\&foo);

use attributes (); # optional, to get subroutine declarations = attributes::get(\&foo); NAME SYNOPSIS attributes - get/set subroutine or variable attributes sub foo : method ; my ($x,@y,%z) : Bent = 1; my $s = sub : method {... ; use attributes (); # optional, to get subroutine declarations

More information

x = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0

x = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0 6 Statements 43 6 Statements The statements of C# do not differ very much from those of other programming languages. In addition to assignments and method calls there are various sorts of selections and

More information

This document describes version 2.10 of Switch, released Dec 29, 2003.

This document describes version 2.10 of Switch, released Dec 29, 2003. NAME Switch - A switch statement for Perl VERSION This document describes version 2.10 of Switch, released Dec 29, 2003. SYNOPSIS use Switch; BACKGROUND case 1 { print "number 1" case "a" { print "string

More information

threads::shared - Perl extension for sharing data structures between threads

threads::shared - Perl extension for sharing data structures between threads NAME VERSION SYNOPSIS threads::shared - Perl extension for sharing data structures between threads This document describes threads::shared version 1.56 use threads; use threads::shared; my $var :shared;

More information

Perl. Interview Questions and Answers

Perl. Interview Questions and Answers and Answers Prepared by Abhisek Vyas Document Version 1.0 Team, www.sybaseblog.com 1 of 13 Q. How do you separate executable statements in perl? semi-colons separate executable statements Example: my(

More information

sottotitolo A.A. 2016/17 Federico Reghenzani, Alessandro Barenghi

sottotitolo A.A. 2016/17 Federico Reghenzani, Alessandro Barenghi Titolo presentazione Piattaforme Software per la Rete sottotitolo BASH Scripting Milano, XX mese 20XX A.A. 2016/17, Alessandro Barenghi Outline 1) Introduction to BASH 2) Helper commands 3) Control Flow

More information

1 Apache2::Filter - Perl API for Apache 2.0 Filtering

1 Apache2::Filter - Perl API for Apache 2.0 Filtering Apache2::Filter - Perl API for Apache 20 Filtering 1 Apache2::Filter - Perl API for Apache 20 Filtering 1 Apache2::Filter - Perl API for Apache 20 Filtering 1 11 Synopsis 11 Synopsis use Apache2::Filter

More information

[Skip ahead to DESCRIPTION if you don't care about the whys and wherefores of this control structure]

[Skip ahead to DESCRIPTION if you don't care about the whys and wherefores of this control structure] NAME Switch - A switch statement for Perl SYNOPSIS use Switch; Perl version 5.12.1 documentation - Switch BACKGROUND case 1 { print "number 1" case "a" { print "string a" case [1..10,42] { print "number

More information

autodie - Replace functions with ones that succeed or die with lexical scope # Recommended: implies 'use autodie qw(:default)'

autodie - Replace functions with ones that succeed or die with lexical scope # Recommended: implies 'use autodie qw(:default)' NAME autodie - Replace functions with ones that succeed or die with lexical scope SYNOPSIS # Recommended: implies 'use autodie qw(:default)' use autodie qw(:all); # Recommended more: defaults and system/exec.

More information

Shells & Shell Programming (Part B)

Shells & Shell Programming (Part B) Shells & Shell Programming (Part B) Software Tools EECS2031 Winter 2018 Manos Papagelis Thanks to Karen Reid and Alan J Rosenthal for material in these slides CONTROL STATEMENTS 2 Control Statements Conditional

More information

Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Chapter 11 Introduction to PHP

Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Chapter 11 Introduction to PHP Chapter 11 Introduction to PHP 11.1 Origin and Uses of PHP Developed by Rasmus Lerdorf in 1994 PHP is a server-side scripting language, embedded in XHTML pages PHP has good support for form processing

More information

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

Index. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309

Index. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309 A Arithmetic operation floating-point arithmetic, 11 12 integer numbers, 9 11 Arrays, 97 copying, 59 60 creation, 48 elements, 48 empty arrays and vectors, 57 58 executable program, 49 expressions, 48

More information

CS251 Programming Languages Handout # 29 Prof. Lyn Turbak March 7, 2007 Wellesley College

CS251 Programming Languages Handout # 29 Prof. Lyn Turbak March 7, 2007 Wellesley College CS5 Programming Languages Handout # 9 Prof. Lyn Turbak March, 00 Wellesley College Postfix: A Simple Stack Language Several exercises and examples in this course will involve the Postfix mini-language.

More information

Client-Side Web Technologies. JavaScript Part I

Client-Side Web Technologies. JavaScript Part I Client-Side Web Technologies JavaScript Part I JavaScript First appeared in 1996 in Netscape Navigator Main purpose was to handle input validation that was currently being done server-side Now a powerful

More information

CS4120/4121/5120/5121 Spring 2016 Xi Language Specification Cornell University Version of May 11, 2016

CS4120/4121/5120/5121 Spring 2016 Xi Language Specification Cornell University Version of May 11, 2016 CS4120/4121/5120/5121 Spring 2016 Xi Language Specification Cornell University Version of May 11, 2016 In this course you will start by building a compiler for a language called Xi. This is an imperative,

More information

Essentials for Scientific Computing: Bash Shell Scripting Day 3

Essentials for Scientific Computing: Bash Shell Scripting Day 3 Essentials for Scientific Computing: Bash Shell Scripting Day 3 Ershaad Ahamed TUE-CMS, JNCASR May 2012 1 Introduction In the previous sessions, you have been using basic commands in the shell. The bash

More information

Functional Programming. Pure Functional Programming

Functional Programming. Pure Functional Programming Functional Programming Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends only on the values of its sub-expressions (if any).

More information

PHP Personal Home Page PHP: Hypertext Preprocessor (Lecture 35-37)

PHP Personal Home Page PHP: Hypertext Preprocessor (Lecture 35-37) PHP Personal Home Page PHP: Hypertext Preprocessor (Lecture 35-37) A Server-side Scripting Programming Language An Introduction What is PHP? PHP stands for PHP: Hypertext Preprocessor. It is a server-side

More information

COMP284 Scripting Languages Lecture 3: Perl (Part 2) Handouts

COMP284 Scripting Languages Lecture 3: Perl (Part 2) Handouts COMP284 Scripting Languages Lecture 3: Perl (Part 2) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool

More information

They grow as needed, and may be made to shrink. Officially, a Perl array is a variable whose value is a list.

They grow as needed, and may be made to shrink. Officially, a Perl array is a variable whose value is a list. Arrays Perl arrays store lists of scalar values, which may be of different types. They grow as needed, and may be made to shrink. Officially, a Perl array is a variable whose value is a list. A list literal

More information

Introduction to Perl. Perl Background. Sept 24, 2007 Class Meeting 6

Introduction to Perl. Perl Background. Sept 24, 2007 Class Meeting 6 Introduction to Perl Sept 24, 2007 Class Meeting 6 * Notes on Perl by Lenwood Heath, Virginia Tech 2004 Perl Background Practical Extraction and Report Language (Perl) Created by Larry Wall, mid-1980's

More information

CS558 Programming Languages Winter 2018 Lecture 4a. Andrew Tolmach Portland State University

CS558 Programming Languages Winter 2018 Lecture 4a. Andrew Tolmach Portland State University CS558 Programming Languages Winter 2018 Lecture 4a Andrew Tolmach Portland State University 1994-2018 Pragmatics of Large Values Real machines are very efficient at handling word-size chunks of data (e.g.

More information

Iterative Languages. Scoping

Iterative Languages. Scoping Iterative Languages Scoping Sample Languages C: static-scoping Perl: static and dynamic-scoping (use to be only dynamic scoping) Both gcc (to run C programs), and perl (to run Perl programs) are installed

More information

# Constructors $smtp = Net::SMTP->new( mailhost ); $smtp = Net::SMTP->new( mailhost, Timeout => 60);

# Constructors $smtp = Net::SMTP->new( mailhost ); $smtp = Net::SMTP->new( mailhost, Timeout => 60); NAME Net::SMTP - Simple Mail Transfer Protocol Client SYNOPSIS DESCRIPTION EXAMPLES # Constructors $smtp = Net::SMTP->new( mailhost, Timeout => 60 This module implements a client interface to the SMTP

More information

CS1150 Principles of Computer Science Methods

CS1150 Principles of Computer Science Methods CS1150 Principles of Computer Science Methods Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Opening Problem Find the sum of integers from 1 to

More information

Relational Operators and if. Class 10

Relational Operators and if. Class 10 Relational Operators and if Class 10 Data Type a data type consists of two things: Data Type a data type consists of two things: a set of values Data Type a data type consists of two things: a set of values

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Fall 2016 Lecture 4a Andrew Tolmach Portland State University 1994-2016 Pragmatics of Large Values Real machines are very efficient at handling word-size chunks of data (e.g.

More information

Modularity and Reusability I. Functions and code reuse

Modularity and Reusability I. Functions and code reuse Modularity and Reusability I Functions and code reuse Copyright 2006 2009 Stewart Weiss On being efficient When you realize that a piece of Perl code that you wrote may be useful in future programs, you

More information

Perl Library Functions

Perl Library Functions Perl Library Functions Perl has literally hundreds of functions for all kinds of purposes: file manipulation, database access, network programming, etc. etc. It has an especially rich collection of functions

More information

SWIFT - CLOSURES. Global Functions Nested Functions Closure Expressions. Have a name. Capture values from enclosing function

SWIFT - CLOSURES. Global Functions Nested Functions Closure Expressions. Have a name. Capture values from enclosing function http://www.tutorialspoint.com/swift/swift_closures.htm SWIFT - CLOSURES Copyright tutorialspoint.com Closures in Swift are similar to that of self-contained functions organized as blocks and called anywhere

More information

Introduction to Perl Session 6. special variables subroutines Introduction to Perl

Introduction to Perl Session 6. special variables subroutines Introduction to Perl 1.0.1.8.6 Introduction to Perl Session 6 special variables subroutines 6/17/2008 1.0.1.8.6 - Introduction to Perl - Special Variables and Subroutines 1 I/O Recap file handles are created using open(f,$file);

More information

Language Evaluation P L COS 301. Fall School of Computing and Information Science University of Maine. Language Evaluation COS 301.

Language Evaluation P L COS 301. Fall School of Computing and Information Science University of Maine. Language Evaluation COS 301. School of Computing and Information Science University of Maine Fall 2018 Outline 1 2 3 4 5 evaluation criteria Early (pre-1970s): more important for machine to read code easily After: realized SW maintenance

More information

GAWK Language Reference Manual

GAWK Language Reference Manual GAWK Language Reference Manual Albert Cui, Karen Nan, Mei-Vern Then, & Michael Raimi So good, you re gonna GAWK. 1.0 Introduction This manual describes the GAWK language and is meant to be used as a reliable

More information

SMURF Language Reference Manual Serial MUsic Represented as Functions

SMURF Language Reference Manual Serial MUsic Represented as Functions SMURF Language Reference Manual Serial MUsic Represented as Functions Richard Townsend, Lianne Lairmore, Lindsay Neubauer, Van Bui, Kuangya Zhai {rt2515, lel2143, lan2135, vb2363, kz2219}@columbia.edu

More information

Arguments of the use overload directive are (key, value) pairs. For the full set of legal keys, see Overloadable Operations below.

Arguments of the use overload directive are (key, value) pairs. For the full set of legal keys, see Overloadable Operations below. NAME overload - Package for overloading Perl operations SYNOPSIS package SomeThing; use overload '+' => \&myadd, '-' => \&mysub; # etc... DESCRIPTION Fundamentals Declaration package main; $a = SomeThing->new(

More information

Learning Perl 6. brian d foy, Version 0.6, Nordic Perl Workshop 2007

Learning Perl 6. brian d foy, Version 0.6, Nordic Perl Workshop 2007 Learning Perl 6 brian d foy, Version 0.6, Nordic Perl Workshop 2007 for the purposes of this tutorial Perl 5 never existed Don t really do this $ ln -s /usr/local/bin/pugs /usr/bin/perl

More information

perl -MO=Deparse[,-d][,-fFILE][,-p][,-q][,-l] [,-sletters][,-xlevel] prog.pl

perl -MO=Deparse[,-d][,-fFILE][,-p][,-q][,-l] [,-sletters][,-xlevel] prog.pl NAME SYNOPSIS DESCRIPTION OPTIONS B::Deparse - Perl compiler backend to produce perl code perl -MO=Deparse[,-d][,-fFILE][,-p][,-q][,-l] [,-sletters][,-xlevel] prog.pl B::Deparse is a backend module for

More information

S206E Lecture 19, 5/24/2016, Python an overview

S206E Lecture 19, 5/24/2016, Python an overview S206E057 Spring 2016 Copyright 2016, Chiu-Shui Chan. All Rights Reserved. Global and local variables: differences between the two Global variable is usually declared at the start of the program, their

More information

CS 105 Perl: Modules and Objects

CS 105 Perl: Modules and Objects CS 105 Perl: Modules and Objects February 20, 2013 Agenda Today s lecture is an introduction to Perl modules and objects, but first we will cover a handy feature Perl has for making data structures. Where

More information

# use a BEGIN block so we print our plan before MyModule is loaded BEGIN { plan tests => 14, todo => [3,4] }

# use a BEGIN block so we print our plan before MyModule is loaded BEGIN { plan tests => 14, todo => [3,4] } NAME SYNOPSIS Test - provides a simple framework for writing test scripts use strict; use Test; # use a BEGIN block so we print our plan before MyModule is loaded BEGIN { plan tests => 14, todo => [3,4]

More information

COMP 2718: Shell Scripts: Part 1. By: Dr. Andrew Vardy

COMP 2718: Shell Scripts: Part 1. By: Dr. Andrew Vardy COMP 2718: Shell Scripts: Part 1 By: Dr. Andrew Vardy Outline Shell Scripts: Part 1 Hello World Shebang! Example Project Introducing Variables Variable Names Variable Facts Arguments Exit Status Branching:

More information

9/21/17. Outline. Expression Evaluation and Control Flow. Arithmetic Expressions. Operators. Operators. Notation & Placement

9/21/17. Outline. Expression Evaluation and Control Flow. Arithmetic Expressions. Operators. Operators. Notation & Placement Outline Expression Evaluation and Control Flow In Text: Chapter 6 Notation Operator evaluation order Operand evaluation order Overloaded operators Type conversions Short-circuit evaluation of conditions

More information

$ftp = Net::FTP->new("some.host.name", Debug => 0) or die "Cannot connect to some.host.name:

$ftp = Net::FTP->new(some.host.name, Debug => 0) or die Cannot connect to some.host.name: NAME Net::FTP - FTP Client class SYNOPSIS use Net::FTP; $ftp = Net::FTP->new("some.host.name", Debug => 0) or die "Cannot connect to some.host.name: $@"; $ftp->login("anonymous",'-anonymous@') or die "Cannot

More information

CSE 374: Programming Concepts and Tools. Eric Mullen Spring 2017 Lecture 4: More Shell Scripts

CSE 374: Programming Concepts and Tools. Eric Mullen Spring 2017 Lecture 4: More Shell Scripts CSE 374: Programming Concepts and Tools Eric Mullen Spring 2017 Lecture 4: More Shell Scripts Homework 1 Already out, due Thursday night at midnight Asks you to run some shell commands Remember to use

More information

CSCI-GA Scripting Languages

CSCI-GA Scripting Languages CSCI-GA.3033.003 Scripting Languages 6/7/2012 Textual data processing (Perl) CS 5142 Cornell University 9/7/13 1 Administrative Announcements Homework 2 due Friday at 6pm. First prelim 9/27, Review on

More information

Background Type Classes (1B) Young Won Lim 6/28/18

Background Type Classes (1B) Young Won Lim 6/28/18 Background Type Classes (1B) Copyright (c) 2016-2017 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2

More information

Lecture 2, September 4

Lecture 2, September 4 Lecture 2, September 4 Intro to C/C++ Instructor: Prashant Shenoy, TA: Shashi Singh 1 Introduction C++ is an object-oriented language and is one of the most frequently used languages for development due

More information

COMS 3101 Programming Languages: Perl. Lecture 1

COMS 3101 Programming Languages: Perl. Lecture 1 COMS 3101 Programming Languages: Perl Lecture 1 Fall 2013 Instructor: Ilia Vovsha http://www.cs.columbia.edu/~vovsha/coms3101/perl What is Perl? Perl is a high level language initially developed as a scripting

More information

Semantic Analysis and Type Checking

Semantic Analysis and Type Checking Semantic Analysis and Type Checking The compilation process is driven by the syntactic structure of the program as discovered by the parser Semantic routines: interpret meaning of the program based on

More information

Arrays (Lists) # or, = ("first string", "2nd string", 123);

Arrays (Lists) # or, = (first string, 2nd string, 123); Arrays (Lists) An array is a sequence of scalars, indexed by position (0,1,2,...) The whole array is denoted by @array Individual array elements are denoted by $array[index] $#array gives the index of

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 4 Thomas Wies New York University Review Last week Control Structures Selection Loops Adding Invariants Outline Subprograms Calling Sequences Parameter

More information

Decaf Language Reference Manual

Decaf Language Reference Manual Decaf Language Reference Manual C. R. Ramakrishnan Department of Computer Science SUNY at Stony Brook Stony Brook, NY 11794-4400 cram@cs.stonybrook.edu February 12, 2012 Decaf is a small object oriented

More information

Topics. Introduction to Repetition Structures Often have to write code that performs the same task multiple times. Controlled Loop

Topics. Introduction to Repetition Structures Often have to write code that performs the same task multiple times. Controlled Loop Topics C H A P T E R 4 Repetition Structures Introduction to Repetition Structures The for Loop: a Count- Sentinels Nested Loops Introduction to Repetition Structures Often have to write code that performs

More information

CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures

CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures Dan Grossman Fall 2014 Hi! I m not Hal J I love this stuff and have taught

More information

An Introduction to Scheme

An Introduction to Scheme An Introduction to Scheme Stéphane Ducasse stephane.ducasse@inria.fr http://stephane.ducasse.free.fr/ Stéphane Ducasse 1 Scheme Minimal Statically scoped Functional Imperative Stack manipulation Specification

More information

CSCI 4152/6509 Natural Language Processing. Perl Tutorial CSCI 4152/6509. CSCI 4152/6509, Perl Tutorial 1

CSCI 4152/6509 Natural Language Processing. Perl Tutorial CSCI 4152/6509. CSCI 4152/6509, Perl Tutorial 1 CSCI 4152/6509 Natural Language Processing Perl Tutorial CSCI 4152/6509 Vlado Kešelj CSCI 4152/6509, Perl Tutorial 1 created in 1987 by Larry Wall About Perl interpreted language, with just-in-time semi-compilation

More information