Perl Challenge Lecturer: Prof. Andrzej (AJ) Bieszczad Phone: “UNIX for Programmers and Users” Third Edition, Prentice-Hall, GRAHAM GLASS, KING ABLES Slides partially adapted from Kumoh National University of Technology (Korea) and NYU
Perl Challenge Prof. Andrzej (AJ) Bieszczad Phone: Exercises #1, #2 Input your name into a variable called $name and then print "Hello, ". my $name; print "Enter your name: "; chomp( $name = ); print "Hello, $name.\n"; Create a subroutine that takes a person's name and prints "Hello,." print "Enter your name: "; chomp( my $name = ); &printName( $name ); sub printName { my $name = $_[0]; print "Hello, $name.\n"; }
Perl Challenge Prof. Andrzej (AJ) Bieszczad Phone: Exercise #3 Write a program that asks a user for five groceries, and then store them (using random access operations) in an array and prints them out in alphabetical order. print "Enter five items from a grocery list:\n"; for( my $i = 0; $i < 5; $i++ ) { print "Enter item $i: "; chomp( $grocerylist[$i] = ); = ); print "\nThe items you entered are:\n"; print ), "\n";
Perl Challenge Prof. Andrzej (AJ) Bieszczad Phone: Exercise #4 Write a program that asks a user for five groceries, but store the groceries into an array using one of the stack operations. (Either push or unshift.) print "Enter five items from a grocery list:\n"; my $input); foreach( 1..5 ) { print "Enter item $_: "; chomp( $input = ); $input ); = ); print "\nThe items you entered are:\n"; print ), "\n";
Perl Challenge Prof. Andrzej (AJ) Bieszczad Phone: Exercise #5 Write a program that uses a subroutine that asks a user for five groceries. After obtaining the list, the program should print the list in alphabetical order. sub input { my $list; for( my $i = 1; $i <=5; $i++ ) { print "Enter grocery $i: "; chomp( my $grocery = ); $grocery ); } } print "Enter five groceries to be sorted and stored in the file \"grocerylist.txt\":\n"; = sort( &input() ); print "\nThe items you entered are:\n"; print ), "\n";
Perl Challenge Prof. Andrzej (AJ) Bieszczad Phone: Exercise #6 Amend program #5 with a subroutine that writes the list of groceries to a file, and then write them to a file in alphabetical order. Modify the input subroutine, so it sorts the list before returning. sub write { my $to_write = join( "\n", ) ); open( OUT, ">grocerylist.txt" ); select OUT; print $to_write; close( OUT ); select STDOUT; } print "Enter five groceries to be sorted and stored in the file \"grocerylist.txt\":\n"; &write( &input() );
Perl Challenge Prof. Andrzej (AJ) Bieszczad Phone: Exercise #7 Write a program that reads the file written in the last exercise, and then prints the contents of the file to the screen in the opposite order that they appeared in the file. sub read { open( IN, $_[0] ); while(my $line = ) { chomp( $line ); $line ); } close( IN ); } print "Opening file grocerylist.txt\n"; print join( "\n", reverse( &read("grocerylist.txt") ) ), "\n";