CS 105 Perl File IO, slices, and array manipulation by odn41067

VIEWS: 5 PAGES: 25

									               CS 105 Perl:
File I/O, slices, and array manipulation

              Curtis Dunham


             February 1, 2010




           Curtis Dunham   CS 105 Perl: File I/O, slices, and array manipulation
Agenda

  We continue our discussion of intermediate Perl techniques
  and, as time permits, venture into more advanced techniques.
      Intermediate iteration
          last and next
      Intermediate I/O
      Special variables
      Slices
      Array manipulation
          push, pop, shift, unshift
          flattening
          splice
          sort
      @ARGV


                          Curtis Dunham   CS 105 Perl: File I/O, slices, and array manipulation
last

  last immediately exits a loop.

  foreach $baz (@baz) {
    if ($baz == $special) {
      last;
    }
    # ...
  }

  Better:

  foreach $baz (@baz) {
    last if $baz == $special;
    # ...
  }


                       Curtis Dunham   CS 105 Perl: File I/O, slices, and array manipulation
next

  next ends the current iteration and starts the next.

  foreach $baz (@baz) {
    if (boring($baz)) {
      next;
    }
    # ...
  }

  Better:

  foreach $baz (@baz) {
    next if boring($baz);
    # ...
  }


                        Curtis Dunham   CS 105 Perl: File I/O, slices, and array manipulation
The default variable: $_



   If you don’t specify a variable name for a foreach loop,
   Perl will automatically use $_.

   foreach (@baz) {
     next if boring($_);
     # ...
   }

   Many syntactical constructs and built-in functions in Perl use $_
   by default.




                         Curtis Dunham   CS 105 Perl: File I/O, slices, and array manipulation
open



  To read or write a specific file, use open.

  open(CONFIG, ’config’);
  while(<CONFIG>) {
    chomp;
    # ...
  }
  close(CONFIG);

  Don’t forget to close files when you’re done with them, too.




                       Curtis Dunham   CS 105 Perl: File I/O, slices, and array manipulation
split
  split is a built-in function that breaks a string into separate
  strings (scalars). By default, it splits $_ wherever there is
  whitespace.

  while(<>) {
    chomp;
    @words = split;
    # ...
  }

  For example:

  $_ = ’high low up down left right’;
  @words = split;
  # @words = (’high’, ’low’, ’up’, ’down’,
  #           ’left’, ’right’);

                        Curtis Dunham   CS 105 Perl: File I/O, slices, and array manipulation
Special Variables




   Perl has many variables that are special or magical.
   $_ is just one of them.
   All of them are documented at perlvar.




                         Curtis Dunham   CS 105 Perl: File I/O, slices, and array manipulation
$0



     $0 is automatically set to the name of the program.
     For instance, if my program is named foo and I run it with
     ./foo, then $0 = ’./foo’.
     This is very handy when combined with a built-in function called
     die.

     die "usage: $0 <input> <output>\n" unless ...




                          Curtis Dunham   CS 105 Perl: File I/O, slices, and array manipulation
Another use for die



  Sometimes you might get some input that you just can’t use,
  but you still can’t ignore it.

  while(<>) {
    chomp;
    die "blah blah" if somethings_wrong($_);
  }




                       Curtis Dunham   CS 105 Perl: File I/O, slices, and array manipulation
push




  push adds elements to the end of an array.

  push @a, 10; # push 10 onto the end of @a
  push @a, @b; # push the entire contents of @b




                       Curtis Dunham   CS 105 Perl: File I/O, slices, and array manipulation
pop




  pop removes the last element of an array and returns it.

  $last = pop @a;




                       Curtis Dunham   CS 105 Perl: File I/O, slices, and array manipulation
shift and unshift



  unshift and shift are like push and pop, respectively, but
  add and remove elements from the beginning of the array.

  unshift @b, @c;
  unshift @b, 1; # insert 1 at $b[0]

  $first = shift @b; # $first = 1




                      Curtis Dunham   CS 105 Perl: File I/O, slices, and array manipulation
Handy array function table




    Array functions    At front       At end
    Add element(s)    unshift         push
    Remove element     shift           pop




                      Curtis Dunham   CS 105 Perl: File I/O, slices, and array manipulation
Arrays as Stacks




  If you restrict yourself to the push and pop functions when
  modifying an array, this results in a container with “LIFO”
  (Last-In, First-Out) behavior; i.e. a stack.




                       Curtis Dunham   CS 105 Perl: File I/O, slices, and array manipulation
Arrays as Queues




  If you restrict yourself to push and shift functions when
  modifying an array, this results in a container with “FIFO”
  (First-In, First-Out) behavior; i.e. a queue.
  You could also use unshift with pop, though I expect the
  former to feel more natural.




                        Curtis Dunham   CS 105 Perl: File I/O, slices, and array manipulation
Slices




   Perl allows you to access multiple elements from an array, hash,
   or list. This subset of scalars in a container is called a slice.

   ($first, $last) = @a[0, -1]; # accesses @a
   ($al, $bob) = @a{’al’,’bob’}; # accesses %a

   Remember the sigil rule!




                         Curtis Dunham   CS 105 Perl: File I/O, slices, and array manipulation
Array slices, graphically




                                    days

                                Sunday
                                Monday
                               Tuesday
           @days[0,6]
                              Wednesday
                              Thursday
                               Friday
                              Saturday




                    Curtis Dunham    CS 105 Perl: File I/O, slices, and array manipulation
Slices as lvalues




   We can assign to slices as well.

   @days[0,6] = (’Sunday’,’Saturday’);
   @dogs{’poodle’,’labrador’} = (’fierce’);




                        Curtis Dunham   CS 105 Perl: File I/O, slices, and array manipulation
List flattening




   When putting arrays in a list, the elements are expanded into
   the containing list. The array does not maintain its identity.
   Another way of saying this is that you can’t create a hierarchy of
   arrays (arrays inside arrays) this way.

   @a = (@b, @c, $a, keys %d);




                         Curtis Dunham   CS 105 Perl: File I/O, slices, and array manipulation
Quote Words - qw()



  Perl provides an easy way to create a list using the qw operator.
  Before:

  @days[0,6] = (’Sunday’,’Saturday’);
  @dogs{’poodle’,’labrador’} = (’fierce’);

  After:

  @days[0,6] = qw(Sunday Saturday);
  @dogs{qw(poodle labrador)} = qw(fierce);




                        Curtis Dunham   CS 105 Perl: File I/O, slices, and array manipulation
splice



  splice is a powerful function that allows you to remove
  scalars from and/or insert scalars into an array.
  splice ARRAY, OFFSET, LENGTH, LIST

   push(@a,$x,$y)              splice(@a,@a,0,$x,$y)
   pop(@a)                     splice(@a,-1)
   shift(@a)                   splice(@a,0,1)
   unshift(@a,$x,$y)           splice(@a,0,0,$x,$y)
   $a[$i] = $y                 splice(@a,$i,1,$y)




                       Curtis Dunham   CS 105 Perl: File I/O, slices, and array manipulation
sort



  sort sorts an array.
  By default, it sorts the array stringwise (like the eq, lt, etc.
  operators).

  @b = sort @a;
  foreach $foo (sort keys %foo) {
    # ...
  }




                         Curtis Dunham   CS 105 Perl: File I/O, slices, and array manipulation
Numeric sort
  By default, sort works like this:

  @bar = sort @foo;
  # same as
  @bar = sort { $a cmp $b } @foo;

  cmp is a stringwise comparison operator.

  # sort numerically - use spaceship
  @bar = sort { $a <=> $b } @foo;

  The code inside the curly braces is a block that will be
  evaluated to provide the relative position of the two elements.
  See perldoc -f sort for all the details.
  The parameters to sort’s comparison block are always $a and
  $b. If $a and $b are already being used, they are automatically
  hidden inside the comparison block (so that they don’t collide).
                         Curtis Dunham   CS 105 Perl: File I/O, slices, and array manipulation
@ARGV



  The command line arguments to a program are automatically
  assigned to @ARGV.

  foreach $arg (@ARGV) {
    # ...
  }
  $first = shift;

  shift without an argument defaults to shifting from @ARGV.




                      Curtis Dunham   CS 105 Perl: File I/O, slices, and array manipulation

								
To top