1/113
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
Name four types of looping constructs.
1. for
2. foreach
3. while
4. do-while
Why do programming languages provide more than one type of loop?
Writability; it allows programmers to choose the best loop construct for the task at hand.
What is short-circuit evaluation?
It is when part of an expression is not evaluated since that part has become irrelevant.
Provide an example of a short-circuit evaluation using Perl.
$x = 3;
if ($x > 0 || $x < 10)
{
# do blah blah blah
}
# the test of $x < 10 is short-circuited since $x > 0 is true
What are overloaded operators?
It is when you define a common operator like + or << for a class in which that operator is not defined.
Explain using an example of when it would be necessary to overload operators.
Suppose you created a Fraction class. You could overload the + and << operators so that you could add or display Fraction objects.
What is a union type?
Like a C++ struct, except the data members do not all exist at the same time. They share one memory space so only one data member may be active at a given time.
Provide a C++ definition of a union that could be helpful in an application.
union payroll
{
int annualSalary;
double hourlyRate;
};
What is a tuple?
An ordered, immutable sequence of elements.
Give an example of a Python tuple.
player = ("Cade", "Cunningham", 25.4, 6.3, 9.4)
immutable
unable to be changed
Who created Perl, and what year was it created?
Larry Wall; 1987
Why was Perl created?
For scripting and string/text manipulation in UNIX-like environments.
- there are many built-in text-manipulation functions and operators that can process text in an easier way compared to traditional languages.
What does Perl stand for?
Practical Extraction and Report Language
T/F: Perl uses a compiler.
F; it uses an interpreter
What new features did Perl 2.0, released in 1988, provide?
- new regexp routines
- support for /(foo | bar)/
- support for /(foo)*/ and /(foo)+/
- \s for whitespace, \S for non-, \d for digit, \D for nondigit
- open pipe to forked off script
- wait, sort operators, file globbing
- foreach loop
What does Perl's original man page highlight?
- interpreted language
- used for scanning arbitrary text files, extracting info from those text files, and printing reports based on that info
- used for system management tasks
- practical (easy-to-use, efficient, complete) rather than beautiful (tiny, elegant, minimal)
- combines best features of C, sed, awk, and sh
- expression syntax similar to C
- translators to turn sed and awk scripts into Perl scripts
What are Perl's strengths?
- feature rich
- Perl community has been contributing and using the language for over 30 years
- there are over 25,000 extension modules
- CPAN - Comprehensive Perl Archive Network
- freely available - binaries or source
- not owned - maintained and ported to other platforms by Wall and other volunteer programmers
- easy access to system calls and interaction with other programs
- can create web applications with CGI (Common Gateway Interface) programming
What are some similar languages to Perl?
- before Perl: based on shell languages, awk, sed, C
- after Perl: Python, PHP
What are some drawbacks to Perl?
- good for writing quick-and-dirty programs, but it is not as practical for writing large software applications
- rich language with many features, so it can get complicated reading someone else's code
What is the status of Perl today?
- current version of Perl is 5.40.1
- popularity has declined over the last decade, losing ground to languages such as Python
- Perl6 is a new sister language that is not intended to replace Perl5 (Perl6 is compiled, object-oriented, functional, uses parallelism and definable grammars)
hash
also called an associative array, is used for data in which each item has a unique attribute, or key
How do you create a hash in Perl?
use the % symbol
example of a hash
%vehicles = ('ABC123', 'John Doe', 'XYZ777', 'Betty Smith', DSNY14', 'Donald Duck', ...);
%vehicles = ( ); (empty)
How do you reference a specific hash?
similar to an array index, specify it by its key, using curly braces instead of brackets
ex. $vehicles{12UNIX} = 'Dennis Ritchie';
if (exists $vehicles{$key})
{
print "Vehicle w/ plate $key exists";
}
Perl hashes example using arrays
@plates = keys % vehicles;
@names = values % vehicles;
foreach $plate (sort keys %vehicles)
{
print "owner: $vehicles{$plate} ";
print "license: $plate\n";
}
How this works:
- It maps license plate numbers (keys) to owner names (values).
- keys % vehicles returns a list of all the license plate numbers
- values % vehicles returns a list of all the owners
- the lists are stored in @plates and @names
- sort allows license plate numbers to be sorted in ascending order
- Since the keys are the plate numbers, the owner is printed out when using $vehicles{$plates} in the foreach loop.
- the license plate number is printed out here since we stored the keys into the plates array.
How do you call a subroutine in Perl?
use the &, but you can call without & if the function is defined before the call
What does @_ return in reference to subroutines?
the number of parameters
ex. $num_params = @_;
What does @_ contain in reference to subroutines?
the actual parameters
ex. $_[0], $_[1], ...
T/F: A function can return a value with the return statement.
T; if no return statement is executed, the subroutine will return the value of the final statement that was performed
example of a Perl subroutine
#!/usr/bin/perl
my ($len, $wid, $price) =
(75, 80, 3.25);
$cost=
&fenceCost($len, $wid, $price);
print "The total cost is $cost\n";
sub fenceCost
{
my ($l,$w,$p) = @_;
my $perimeter = 2 $l + 2 $w;
my $total = $perimeter * $p;
return $total;
}
global scope
refers to a variable that is available to all parts of a script and exists as long as the script is running
local scope
refers to a variable that has limited scope and might pop in and out of existence depending on what part of the script is currently executing
T/F: Global variables are easy to create and easy to use in Perl.
T; in fact, any variable not explicitly declared with local or my is automatically a global variable
Why are global variables not good?
- large scripts are more difficult to debug when only globals are used
- questions could arise like: Where did that variable come from? When does it get updated? What is it doing?
- variable names may accidentally be used multiple times
- creating reusable Perl libraries is a nightmare
local keyword in Perl
specifies that variables will be local to the currently executing block , loop, or subroutine. The variable is also available to all nested subroutines.
my keyword in Perl
specifies that those variables are local to the current block, loop, or subroutine. It is not available to nested subroutines.
using my and local with more than one variable
must be placed within parenthesis
ex. local ($x, $y);
Example: Local vs. My
study this example and trace through the code in PerlSubroutines powerpoint
reference parameters
the argument list that you get inside your subroutine via @_ are implicit references to the values that were passed in from outside
Do variables passed as parameters have their values modified if you modify the contents of the @_ array itself inside the body of the subroutine?
yes
example of using reference parameters
#!/usr/bin/perl
@prices = (24.95, 35.75, 55.69, 88.59);
print "Prices before the sale\n";
&show(@prices);
&sale(@prices);
print "Prices after the sale\n";
&show(@prices);
sub show {
for (my $i=0; $i < @_; $i++) {
printf("\$%4.2f\n", $_[$i]);
}
}
sub sale {
for (my $i=0; $i < @_; $i++) {
$_[$i] *= 0.95;
}
}
example of recursion with Perl
#!/usr/bin/perl
sub factorial {
my $num = $_[0];
return (1) if ($num <=1);
return ($num * factorial($num-1));
}
print factorial(8);
data type
defines a collection of data values and a set of predefined operations on those values
Which language introduced user-defined data types?
ALGOL 68
user-defined data types
- data structure that is designed for a specific need
- improved readability through the use of meaningful names for types
- allow type checking of the variables of a special category of use
- aids modifiability; programmers can change the type of category of variables in a program by changing a type definition statement only
abstract data types
interface of a type, which is visible to the user, is separated from the representation and set of operations on values of that type, which are hidden from the user; all types provided by high-level programming languages are of this kind
descriptor
collection of the attributes of a variable
object
values of a variable and the space it occupies; more clear definition: instances of user-defined and language-defined abstract data types
primitive data types
data types that are not defined in terms of other types
What types of integers does Java have?
byte, short, int, and long
twos complement
way computers store negative numbers; formed by taking the logical complement of the positive version of the number and adding 1
When were Boolean types introduced?
came with the creation of ALGOL 60
slices
references to substrings of a given string
library functions for character strings in C and C++
- strcpy (moves strings)
- strcat (catenates one given string onto another)
- strcmp (lexigraphically compares two given strings)
- strlen (returns the number of characters, not counting the null character, in the given string)
enumeration type
one in which all the possible values, which are named constants, are provided, or enumerated, in the definition
ex in C++:
enum colors {red, blue, green};
colors myColor = blue, yourColor = red;
myColor++ assigns green to myColor since next in value order
What's another term for an array?
finite mappings
using negative subscripts in Perl
- subscript value is an offset from the end of the array
- ex. if a list had 5 elements, $list[-2] references the element with subscript 3 (subscript range is 0..4)
static array
one in which subscript ranges are statically bound and storage allocation is static (done before run time)
fixed stack-dynamic array
one in which the subscript ranges are statically bound, but allocation is done at declaration elaboration time during execution
fixed heap-dynamic array
similar to fixed stack-dynamic array, in that the subscript ranges and the storage bindings are both fixed after storage is allocated; difference is storage is allocated from the heap, rather than the stack
heap-dynamic array
one in which binding of subscript ranges and storage allocation is dynamic and can change any number of times during the array's lifetime
examples of array types in C and C++
- arrays with static keyword are static
- regular arrays without keyword are fixed stack-dynamic arrays
- for dynamic arrays, new and delete are used to manage heap storage
rectangular array
multidimensional array in which all of the rows have the same number of elements and all of the columns have the same number of elements
jagged array
array where lengths of rows don't have to be the same
What is the equivalent of associative arrays in Python and Perl?
Python: dictionaries
Perl: hashes
How is a tuple different from a record?
elements are not named; don't have a particular type
dangling pointer/dangling reference
pointer that contains the address of a heap-dynamic variable that has been deallocated; worst case could cause store merger to fail in storage management system
ex in C++:
int * arrayPtr1;
int * arrayPtr2 = new int[100]; arrayPtr1 = arrayPtr2;
delete [] arrayPtr2;
// Now, arrayPtr1 is dangling, because the heap storage to which it was pointing has been deallocated.
lost heap-dynamic variable/memory leakage
allocated heap-dynamic variable that is no longer accessible to the user program; garbage
- usually caused by having a pointer point to a newly created heap-dynamic variable, and then the pointer is changed to point to another newly created dynamic variable without deallocating or moving previous variable
reference type
similar to a pointer, but pointers refer to address in memory while this refers to an object or a value in memory
T/F: A programming language is strongly typed if type errors are always detected.
T
data type vs. type system
data type: defines a set of values and a collection of operations on those values
type system: set of types and the rules that govern their use in programs
referential transparency
where any two expressions in the program that have the same value can be substituted for one another anywhere in the program, without affecting the action of the program
pass-by-value
the value of the actual parameter is used to initialize the corresponding formal parameter, which then acts as a local variable in the subprogram, thus implementing in-mode semantics
pass-by-result
implementation model for out-mode parameters; no value is transmitted to the subprogram. The corresponding formal parameter acts as a local variable, but just before control is transferred back to the caller, its value is transmitted back to the caller's actual parameter, which obviously must be a variable.
- has issue of order mattering in calling function parameters
pass-by-value-result (pass-by-copy)
implementation model for inout-mode parameters in which actual values are copied
- combo of pass-by-value and pass-by-result
- value of actual parameter is used to initialize the formal parameter, which then acts as a local variable
- at subprogram termination, the value of the formal parameter is transmitted back to the actual parameter
pass-by-reference
second implementation model for inout-mode parameters
- rather than copying data values back and forth, it transmits an access path, usually just an address, to the called subprogram
- the called subprogram is allowed to access the actual parameter in the calling program unit; the actual parameter is shared with the called subprogram
- efficient in both time and space
pass-by-name
inout-mode parameter transmission method that does not correspond to a single implementation model; the actual parameter is, in effect, textually substituted for the corresponding formal parameter in all its occurrences in the subprogram
- complex and inefficient, so isn't used very often
What does chomp( ) do?
removes whitespace from variable
How does Perl compare strings?
uses eq; to compare numerical values, uses ==
What is a dynamic webpage?
a webpage that changes
CGI
defines how web server and program communicate
T/F: Some query strings should be hidden.
T; things like passwords must be secure
How do you change file permissions?
use change mod (chmod)
- read - 4
- write - 2
- execute - 1
- first field is my permissions, second is group permissions, and third is outside group permissions
- add together permissions to specify how you want the file to be visible
- ex. chmod 755 allows r, w, and e for me, r and e for group and outside group (doesn't allow editing to anyone but me)
command line switches vs. arguments
arguments are required, whereas switches are optional
ex. of argument: cd dirname
ex. of switch: ls -l
methodology
process you use to answer your research question
$x = 8.9;
printf("x is %7.2f\n", $x);
output: x is 8.90
- 7.2f specifies that there can be 7 total characters (including characters before, decimal point, and characters after), and 2 characters after the decimal point
- example above has 4 total characters (but could have up to 7)
file processing modes in Perl
3 file modes: read, write, append
- to specify write, use >file.txt
- to specify append, use >>file.txt
write vs. append
- write: overwrites file
- append: adds to end of file, keeping existing contents
opening/closing a Perl file
open(FP, "file.txt") || die("bye");
- makes sure if file doesn't open, program terminates
close(FP);
reading data from a file into an array/list line-by-line
@data =
How do you calculate the time it takes to complete a task?
you take into account the total number of items to operate on and the number of processes available
- ex. Suppose it takes 1 ms to add 2 matrices. How long would it take to add 8 matrices?
sum = a0 + a1 + a2 + a3 + a4 + a5 + a6 + a7
Time(n = 8, p = 1) = 7 ms (must add a0 + a1, then each one incrementally, resulting in 7 times)
Time(n = 8, p = 4) = 3 ms (must add a0 + a1, a2 + a3, a4 + a5, a6 + a7, then sum1 + sum2, sum3 + sum4, then sum + sum)
- more processors, less time
How do you calculate speedup?
divide the time it takes with one processor by the time it takes with multiple processors
ex. T(n = 8, p = 1)/T(n = 8, p = 4) = 7 ms / 3 ms = 2.3
How do you calculate efficiency?
Divide speedup by the given multiple processors.
ex. S(n = 8, p = 4) / p = 4 => (7/3) / 4 => 7/12 => about 58%
What are you assuming when calculating time, speedup, and efficiency?
1. Tcomm = 0
2. processes are homogenous
3. processes are not doing the work
process
active instance of a program
What are the different types of interprocess communication (IPC)?
1. file (one-way)
2. pipe (one-way or two-way; must be related, on same computer)
3. socket (one-way or two-way; must have IP address and port # since on separate computers)
4. RPC (remote procedure call); allows computer to run a function on another computer
5. RMI (remote method invocation); objects are passed rather than just data like with RPC
What does $result = 'finger'; do?
shows everyone using server
What does exec('ls'); do?
leaves program, then does ls command
What does grep do?
searches files