diff options
| author | Sean Nam <namsangwoo1@gmail.com> | 2017-02-09 17:10:03 -0800 | 
|---|---|---|
| committer | Sean Nam <namsangwoo1@gmail.com> | 2017-02-09 17:10:03 -0800 | 
| commit | 5254804c1ccf51fb3c3c500a7095dd8408371837 (patch) | |
| tree | cade605f3e011f8ac0d46ef74380c632e5502f99 /perl.html.markdown | |
| parent | 52ff8f41e4ef9de074081b5ef22c5dfa4dd86f0a (diff) | |
| parent | 7f0fff0adf38fb47b36da4a8c319c6c9c28c546d (diff) | |
Merge remote-tracking branch 'upstream/master'
Diffstat (limited to 'perl.html.markdown')
| -rw-r--r-- | perl.html.markdown | 27 | 
1 files changed, 27 insertions, 0 deletions
| diff --git a/perl.html.markdown b/perl.html.markdown index 3cbd2801..a29fdf1f 100644 --- a/perl.html.markdown +++ b/perl.html.markdown @@ -51,6 +51,13 @@ my @mixed   = ("camel", 42, 1.23);  # indicate one value will be returned.  my $second = $animals[1]; +# The size of an array is retrieved by accessing the array in a scalar +# context, such as assigning it to a scalar variable or using the +# "scalar" operator. + +my $num_animals = @animals; +print "Number of numbers: ", scalar(@numbers), "\n"; +  ## Hashes  #   A hash represents a set of key/value pairs: @@ -67,6 +74,11 @@ my %fruit_color = (  # Hash elements are accessed using curly braces, again with the $ sigil.  my $color = $fruit_color{apple}; +# All of the keys or values that exist in a hash can be accessed using +# the "keys" and "values" functions. +my @fruits = keys %fruit_color; +my @colors = values %fruit_color; +  # Scalars, arrays and hashes are documented more fully in perldata.  # (perldoc perldata). @@ -144,6 +156,12 @@ for (@elements) {    print;  } +# iterating through a hash (for and foreach are equivalent) + +foreach my $key (keys %hash) { +  print $key, ': ', $hash{$key}, "\n"; +} +  # the Perlish post-condition way again  print for @elements; @@ -170,8 +188,11 @@ $x =~ s/foo/bar/g;        # replaces ALL INSTANCES of foo with bar in $x  # You can open a file for input or output using the "open()" function. +# For reading:  open(my $in,  "<",  "input.txt")  or die "Can't open input.txt: $!"; +# For writing (clears file if it exists):  open(my $out, ">",  "output.txt") or die "Can't open output.txt: $!"; +# For writing (appends to end of file):  open(my $log, ">>", "my.log")     or die "Can't open my.log: $!";  # You can read from an open filehandle using the "<>" operator.  In @@ -182,6 +203,12 @@ open(my $log, ">>", "my.log")     or die "Can't open my.log: $!";  my $line  = <$in>;  my @lines = <$in>; +# You can write to an open filehandle using the standard "print" +# function. + +print $out @lines; +print $log $msg, "\n"; +  #### Writing subroutines  # Writing subroutines is easy: | 
