$x = sub{bar->new(@_)};alternatively:
$x->("thing1","thing2");
bless \$x, "bar";
(\$x)->new("thing1","thing2");
As an example:
sub fullnameURL { return "file://" . realpath(cwd() . "/" . shift);
}
Learn syntax for calls to
print Data::Dumper->Dump( [ \@checkboxlist ],
[qw(*checkboxlist)] ), "\n"
print Data::Dumper->Dump( [ \%checkboxlists ],
[qw(*checkboxlists)] ), "\n"
Contrast that with the syntax of Data::Dumper::Simple,
i.e.
print
Dumper(@checkboxlist,%checkboxlists),"\n";
sub is_item {
my $retval = 0;
if (/^[A-Z]+[ .,]/ and $previous =~ /^$/) {{
next if /^ABOUT PROJECT GUTENBERG-TM ETEXTS/;
next if /^A /;
next unless /^A/;
next if /AUTHORITIES\.\s*-/;
next if (/^A. / and $a_found == 1);
$a_found = 1 if /^A./;
$retval = 1;
}}
$previous = $_;
return $retval;
}
The trick here is the double braces, that 'block' the normal
if statement block;
return wantarray ? () : undef;
sub set_mode ($\@);# This is the declaration...
sub set_mode ($\@) {
our(@array,$val);
local($val,*array) = @_;
splice(
@array, 1, 0,
hidden(
-name => 'mode',
-value => $val,
-override => 1,
)
);
}
In order to differentiate text and variable names in an interpolated string.
At least one thing to remember is that <$fh> is not the same as < $fh>notice the space after <, one is a file handle and the other is a 'glob'! To use <> to slurp a file, first set $/ to either 0777octal, or 'undef' it. An example of 'safe' slurping:
# FILE is already open ...
{
local $/ = undef;
$slurp = <FILE>;
}
# Or for __DATA__ try ...
my $data = do { local $/; <DATA> };
To apply a change to each element of an array:
$_ *= 2 for @rray;
To create a copy of an array with changes:
@copy = map { $_ * 2 } @rray;
To process an array with index number and current value of indexed element:
my @ARRAY = (...);
my @result = map {
do something with $_ and $ARRAY[$_]
} 0..$#ARRAY;
Then, $_ is giving you the index of the element, and
you indirect it to get to the element itself.
Interpolation is on by default, or made explicit by the use of double quotes around RAW. Single quotes turn interpolation off. Don't forget the semi-colon after RAW!
A correction from Aristotle concerning reading line pairs from either STDIN or __DATA__
#!/usr/bin/perl -w use strict; my %bookmark; my %url; while (<>) { my $name = <>; $url{$name} = $_; } for (sort keys %bookmark) { print $bookmark{$_}; print $_; }Here is a piece sugar that allows a reference used in a sub call to be converted back to it's original form:
sub get_firstline { my @lyrics = @{ +shift }; my $firstline; for (@lyrics) { next if (/chorus/i); next unless (/^\w/); $firstline = $_; last; } return $firstline; }An alternative to the form of the second line is:
my @lyrics = { shift() };An example of both a filter and map:
my @list; my $filename_in = $ARGV[0]; if ( $filename_in !~ /\.glo$/i ) { $filename_in .= '.glo'; } open( FILE_IN, $filename_in ) or die "Couldn't open input file '$filename_in': $!\n"; @list = map {chomp;$_} <FILE_IN>;This piece expands wildcards on the command line and then offers each for futher work.
for (map { glob } @ARGV) { # $_ is the next file to process... }As an alternative to the above:
BEGIN { @ARGV = map { glob } @ARGV; } ... foreach (@ARGV) { # $_ is the next file to process... }Need to muck about with STDOUT? Try:
sub wrapper { my $saver = new SelectSaver(shift); $main::{ $_[0] }( $_[1] ); } sub myFunction { my $filename = shift; print "\$filename = '$filename'\n"; do domething here... }Note: The
$main::
syntax allows
use strict;
without complaints about the coderef! Also
note that this code will require a use
SelectSaver;
.
Here is a way of managing default parameters (options etc.) in a function call...
#!/perl/bin/perl # # frag.pl -- 'default' parameter options manager demo... use strict; use warnings; use diagnostics; use Carp; myfunction(optionA=>'12',optionD=>'test'); sub myfunction { my %defs = ( optionA=>2e6, optionB=>'defA', optionC=>'defB' ); my %user = ( %defs, @_ ); my %opts; @opts{keys %defs} = delete @user{keys %defs}; carp "Unknown options: '@{[ %user ]}' ignored." if %user; # %opts user known user supplied options # defaults for unsupplied options # Warning issued about unknown options # do stuff. for (keys %opts) { print "$_='$opts{$_}'\n"; } }
#!/perl/bin/perl # # filter.pl -- One liner goes here. use strict; use warnings; use diagnostics; use Getopt::Long; use Pod::Usage; our $VERSION = '0.01'; GetOptions( 'debug=i' => \( my $debug = 0 ), 'help|?' => \( my $opt_help ), 'man' => \( my $opt_man ), 'version' => \( my $opt_version ), ) or pod2usage(2); if ($opt_version) { print "filter.pl vrs. $VERSION\n"; exit; } pod2usage(1) if $opt_help; pod2usage( -verbose => 2 ) if $opt_man; pod2usage("$0: No files given.") if ( @ARGV == 0 ); for (map { glob } @ARGV) { filter($_); } sub filter { my $file = shift; print "\$ARGV[$n]='$file'\n"; $n++; } __END__ =head1 NAME filter - Given input, use filter to change it to output. =head1 SYNOPSIS filter [options] filespec Options: -debug set debug level, default is off -help brief help message -man full documentation -version version number Switches that don't define a value can be done in long or short form. eg: filter --man filter -m =head1 OPTIONS =over 8 =item B<-debug> Display debug information as program is executed. Control is set by level of the value passed on the command line. Default value is off (debug == 0). =item B<-help> Print a brief help message and exit. =item B<-man> Print the manual page (full documentation) and exit. =item B<-version> Print the version number and exit. =back =head1 DESCRIPTION This is a template for generic file filter. The description goes here. =head1 AUTHOR Hugh S. Myers hsmyers@sdragons.org =head1 BUGS None that I know of. =head1 TODO Not yet, just started! =head1 UPDATES Not yet, just started! =cut
'open' Mode | 'fopen' Mode | 'sysopen' Flags |
< | r | O_RDONLY |
> | w | O_WRONLY | O_CREAT | O_TRUNC |
>> | a | O_WRONLY | O_APPEND | O_CREAT |
+< | r+ | O_RDWR |
+> | w+ | O_RDWR | O_CREAT | O_TRUNC |
+>> | a+ | O_RDWR | O_APPEND | O_CREAT |
Regex | Description |
+ | Quantifier. Match the previous pattern one or more times. |
* | Quantifier. Match the previous pattern zero or more times. |
? | Quantifier. Match the previous pattern zero or one times. |
{n,m} | Quantifier. Denotes the minimum n and maximum m match count. {n} means exactly n times; {n,} at least n times. |
. | Match any character, except newline. In single-line mode matches newlines as well. |
(…) | Groups a series of pattern elements to a single element. The text the group matches is captured for later use. |
^ | Match the beginning of the target. In multiline mode, also match after every newline. |
$ | Match the end of the line, or before a final newline. In multiline mode, also match before every newline. |
[…] | Class of characters to match. [^…] inverts class. |
…|…|… | 'Or-ed' match, left to right, until success. |
(?#text) | Comment. |
(?[modifier] : …) | Like (…) but does not capture the text it matches. modifier can be one or more of i, m, s, or x. Modifiers can be switched off by preceding the letter(s) with a minus sign, e.g., (?si-xm). |
(?=pattern) | Zero-width positive look-ahead assertion. |
(?!pattern) | Zero-width negative look-ahead assertion. |
(?<=pattern) | Zero-width positive look-behind assertion. |
(?<!pattern | Zero-width negative look-behind assertion. |
(?{code}) | Executes Perl code while matching. Always succeeds with zero width. Can be used as the condition in a conditional pattern selection. If not, the result of executing code is stored in $^R. |
(??{code}) | Executes Perl code while matching. Interprets the result as a pattern. |
(?>…) | Like (?:…), but prevents backtracking inside. |
(?(cond)ptrue[|pfalse]) | Selects a pattern depending on the condition. cond should be the number of a parenthesized subpattern, or one of the zero-width look-ahead, look-behind and evaluate assertions. |
(?modifier) | Embedded pattern-match modifier. modifier can be one or more of i, m, s, or x. Modifiers can be switched off by preceding the letter(s) with a minus sign, e.g., (?si-xm). |
\ | Escapes any special meaning of non-alphanumeric characters. |
\1...\n | Escape. Refers to matched subexpressions, grouped with (). |
\w | Escape. Matches alphanumeric plus _, \W matches non-\w. |
\s | Escape. Matches whitespace. \S matches non-\s. |
\d | Escape. Matches numeric. \D matches non-\d. |
\A | Escape. Matches the beginning of the string. |
\Z | Escape. Matches the end of the string, or before a newline at the end. |
\z | Escape. Matches the physical end of the string. |
\b | Escape. Matches word boundaries. \B matches non-word boundaries. |
\G | Escape. Matches where the previous search with a g modifier left off. |
\pp | Escape. Matches a named property. \Pp matches non-p. Use \p{prop} for names longer than one single character. |
\X | Escape. Match extended Unicode “combining character sequence.” |
\C | Escape. Match a single 8-bit byte. |
$& | Variable. The string that matched. |
$` | Variable. The string preceding the match. |
$' | Variable. The string following the match. |
$n | Variable. The first through n grouped subexpression. |
$+ | Variable. The last subexpression that matched. |
@- | Variable. The starting offsets of the match and submatches. |
@+ | Variable. The ending offsets of the match and submatches. |
c | Modifier. (With g) prepares for continuation. |
g | Modifier. Matches as many times as possible. |
i | Modifier. Case-insensative match. |
o | Modifier. Interpolate variables only once. |
m | Modifier. Treat the string as multiple lines, ^ and $ will match at embedded newline characters. |
s | Modifier. Treat the string as a single line, . will match embedded newline characters. |
x | Modifier. Allow for whitespace and comments within the expression. |
These are not in order and they are not optional. Just buy them. Do it now...
Effective Perl Programming 2nd Edition, Joseph N. Hall, Joshua A. McAdams and brian d foy. Addison Wesley, Boston, MA. 2010If as some insist, you need to know what order to purchase these in, then the must haves are in the following order:
Note: These are all subject to more recent editions!
When it comes to books, there is never and end to lists! In particular there are four that make a solid 'course' on Perl and they are listed in the natural order for purchase.
Learning Perl 5th Edition (6th just hit the streets!), Randal L. Schwartz, Tom Phoenix and brian d foy. O'Reilly, Sebastopol, CA. 2008.'Vernacular' Version 1.27 Fri Sep 21 12:36:42 2012