-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathperl_cheatsheet2.pl
437 lines (352 loc) · 10.2 KB
/
perl_cheatsheet2.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
#!/usr/bin/perl -w
#
# written by Nick Shin - [email protected]
# the code found in this file is licensed under:
# - Unlicense - http://unlicense.org/
#
# this file is from https://github.com/nickshin/CheatSheets/
#
#
# this file contains some uses of:
# - file IO
# - forking
# - arrays, arrays of arrays, etc.
# - hashes, hashes of arrays, etc.
# - references to functions
#
# and some of my other most used perl snipets, boiler plate, etc.
#
#
# to run:
# perl perl_cheatsheet2.pl
#
#
# best viewed in editor with tab stops set to 4
# NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
use strict;
use warnings;
# bring in another perl file and using it
require "./perl_cheatsheet1.pl.inc";
use vars qw( @localtime_info $cur_time_full );
# test fileIO folder...
my $testdir = "test_X";
# FILE STUFF {{{
# ----------------------------------------
sub file_io_tests
{
print "\n*** file_io_tests\n";
my $param1 = shift;
if ( ! $param1 ) { $param1 = "nothing"; }
my $here_document = <<__END_COMMUNICATION__;
This is a here document section.
Also called: here-document, heredoc, hereis, here-string or here-script.
The quote ['], double quote ["], continue marker "\\" or the use of concatenation
operators are not needed for these multi line strings.
Note, when printing this "string" (either to stdout or to a file), certain
characters still needs to be escaped. for example, using the \$ character,
will be considered as variable [$param1].
Take note of how the [%] is escaped below.
__END_COMMUNICATION__
$here_document =~ s/%/%%/g; # escape %
if ( ! -d $testdir ) # check if directory exists
{ `mkdir -p $testdir`; }
my $filename = "$testdir/perl_testfile.txt";
if ( -e $filename ) # check if file exists
{ unlink $filename; } # delete file
# write out a file
open FH, "> $filename" || die "unable to open $filename: $!";
printf FH $here_document;
close FH;
# append to a file
open FH, ">> $filename" || die "unable to open $filename: $!";
printf FH $here_document;
close FH;
# read in a file
open FH, "< $filename" || die "unable to open $filename : $!";
my @lines_of_text = <FH>;
close FH;
# loop labels
A_LOOP: foreach ( 0 .. 10 ) {
print "before text: $_\n";
THE_TEXT: foreach my $line ( @lines_of_text ) {
print "$line";
next if ( ! ( $line =~ /^Also/ ) );
last A_LOOP if ( $_ > 1 );
print "inside another loop: $_\n\n";
last;
} }
print "\nsearching for all test_* folders:\n";
foreach( "A" .. "Z" ) {
my $dir = "test_$_";
if ( -d $dir )
{ print "\t$dir found\n"; }
}
# file globbing
print "\nglobbing all files...\n";
my @files = glob "*";
if ( @files ) {
print "files found:\n";
foreach my $file ( @files ) {
print "\t$file\n";
} }
}
# FILE STUFF }}}
# FORK {{{
# ----------------------------------------
sub fork_tests
{
print "\n*** fork_tests\n";
my @wget_children = ();
# parallel gets
my $pid = fork(); if ( $pid != 0 ) { push(@wget_children, $pid); } else {
wget_simple( "'http://www.google.com/'", "$testdir/wget_test_google.html" );
exit(0);} $pid = fork(); if ( $pid != 0 ) { push(@wget_children, $pid); } else {
wget_simple( "'http://www.ipchicken.com/'", "$testdir/wget_test_ipchicken.html" );
exit(0);} $pid = fork(); if ( $pid != 0 ) { push(@wget_children, $pid); } else {
wget_simple( "'http://www.dyndns.com/'", "$testdir/wget_test_dyndns.html" );
exit(0);}
foreach (@wget_children) { waitpid($_, 0); }
print "fork tests done\n";
}
# FORK }}}
# ARRAYS {{{
# ----------------------------------------
# push() - adds an element to the end of an array.
# unshift() - adds an element to the beginning of an array.
# pop() - removes the last element of an array.
# shift() - removes the first element of an array.
# delete $array[index] - removes an element by index number
sub function_parameters
{
my $param1 = shift;
my ( $param2, @params ) = @_;
print "function_parameters are:\n";
print "param1 is: $param1\n"; # a
print "param2 is: $param2\n"; # b
print "params are:\n";
foreach( @params ) # c d e f
{ print "\t$_\n"; }
print "\n";
}
sub array_reference_example
{
$_[0] = "hh"; # this stomps on $item1 (i.e. $param1) even though not passed as reference
my ( $item1, $item2, $an_array ) = @_;
push @{$an_array}, $item1;
# $$item1 = "ii"; # illegal with strict
$$item2 = "zz";
}
sub array_tests
{
print "\n*** array_tests\n";
my @params = ( "a" .. "f" );
function_parameters( @params );
print "array_reference_example: ";
my $param1 = "gg";
my $param2 = "xx";
array_reference_example( $param1, \$param2, \@params );
foreach ( @params )
{ print "$_ "; }
print "\n\tparam1: $param1\tparam2: $param2\n\n";
# the different ways of assigning to/from arrays
my ( $year, $month, $day ) = split( /-/, $cur_time_full ); # string to array
my @fake_timestamp = ( $year, $month, $day );
my $localtime_smashed = join " ", @fake_timestamp; # array to string
print "assigning arrays results: $localtime_smashed\n\n";
# arrays of arrays
my @snp500 = ( "^GSPC", "SP500", "\$SPX", "S&P 500" );
my @nyse = ( "^NYA", "NYA", "\$NYA", "NYSE Composite Index" );
my @array_of_arrays =
( # yahoo bigcharts stockcharts fullname
# dow
[ "^DJI", "DJIA", "\$INDU", "Dow Jones Industrial Average" ],
# nyse
[ @nyse ],
# nasdaq
[ "^IXIC", "NASDAQ", "\$COMPQ", "NASDAQ Composite" ],
);
print "arrays_of_arrays are:\n";
foreach ( @array_of_arrays ) {
my ( $yahoo_sym, $mwatch_sym, $schart_sym, $fullname ) = @$_;
print "bigchart $mwatch_sym symbol is for $fullname\n";
}
# replace an array element with an array
@{ $array_of_arrays[1] } = @snp500;
# push an array to an array
push @{ $array_of_arrays[@array_of_arrays] }, @nyse;
print "\narrays_of_arrays again are:\n";
foreach ( @array_of_arrays ) {
my ( $yahoo_sym, $mwatch_sym, $schart_sym, $fullname ) = @$_;
print "bigchart $mwatch_sym symbol is for $fullname\n";
}
# slice n splice
print "\nslice n splice:\n";
my @nums = (1..201);
my @slicenums = @nums[10..20,50..60,190..200]; # ranged slice
print "@slicenums\n";
@nums = ( 0 .. 10 );
splice(@nums, 2,5,21..25); # replaces
print "@nums\n";
}
# ARRAYS }}}
# HASHES {{{
# ----------------------------------------
# subroutine with hash parameter:
# http://www.troubleshooters.com/codecorn/littperl/perlsub.htm
# o hash input argument only
# o hash input/output argument
# http://www.troubleshooters.com/codecorn/littperl/perlfuncorder.htm
# o prototyped hash argument
sub hash_reference1_example
{
print "\nhash_reference_example:\n";
my %entries = %{$_[0]}; # input argument only
my $item = "";
# note $_ is pointing to an array
# to print that array, note it as: @$_
while ( ( $item, $_ ) = each( %entries ) )
{ print "\t$item - @$_\n"; }
}
sub hash_reference2_example
{ # input/output
${$_[0]}{"XXX"} = [ "xxxing", "xxx", "Dummy Entry" ];
}
sub hash_tests
{
print "\n*** hash_tests\n";
my @an_array = ( "dmcing", "dmc");
my %hash_of_arrays =
( # code label short long description
"AC" => [ "alternating", "alt", "Alternating Current" ],
"DC" => [ "direcct", "dir", "Direct Current" ],
"RUN" => [ "running", "run", "Running on Empty" ],
);
hash_reference1_example( \%hash_of_arrays );
hash_reference2_example( \%hash_of_arrays );
print "\nhash_of_arrays by key:\n";
foreach my $key ( sort keys %hash_of_arrays ) {
# array items by array assignment -- the short way
my ( $labelname, $shortname, $longname ) = @{ $hash_of_arrays{ $key } };
print "$key\t$labelname\t$shortname\t$longname\n";
# array items by index -- the long way
for my $i ( 0 .. $#{ $hash_of_arrays{$key} } ) {
my @entry = split ' ', $hash_of_arrays{$key}[$i];
foreach( @entry )
{ print "\t$_"; }
print "\n";
} }
# replace
my $ll = "Devastating Microphone Control";
$hash_of_arrays{ "DC" } = [ @an_array, $ll ];
# add new hash, and then push another element to the array at the end...
# i.e. doing this the long way for an example...
$hash_of_arrays{ "DMC" } = [ @an_array ];
push @{ $hash_of_arrays{ "DMC" } }, $ll;
print "\nhash_of_arrays by key again:\n";
foreach my $key ( sort keys %hash_of_arrays ) {
# array items by array assignment -- the short way
my ( $labelname, $shortname, $longname ) = @{ $hash_of_arrays{ $key } };
print "$key\t$labelname\t$shortname\t$longname\n";
}
}
# HASHES }}}
# FUNCTION {{{
# ----------------------------------------
sub funcref_test
{
print "\n*** function_reference\n";
my $results = "";
my $method = \&func_ref1;
for ( 0 .. 2 ) { $method->( $_, \$results, \$method ); }
print "results:\n$results\n";
print "function_reference tests done\n";
}
sub func_ref1
{
$_ = shift;
my ( $results, $method ) = @_;
$$results .= "$_: func_ref1\n";
print "\t$_ - in func_ref1()\n";
$$method = \&func_ref2;
}
sub func_ref2
{
$_ = shift;
my ( $results, $method ) = @_;
$$results .= "$_: func_ref2\n";
print "\t$_ - in func_ref2()\n";
$$method = \&func_ref1;
}
# FUNCTION }}}
# HOUSEKEEPING {{{
# ----------------------------------------
sub usage
{
print "USAGE:\n";
print "\n";
print " $0 commands\n";
print "\n";
print "where commands are:\n";
print "\n";
print " all - run all test functions\n";
print " o this is equivalent to:\n";
print " $0 file fork array hash func\n";
print "\n";
print " file - file IO tests\n";
print "\n";
print " fork - fork tests\n";
print "\n";
print " array - array tests\n";
print "\n";
print " hash - hash tests\n";
print "\n";
print " func - function reference tests\n";
print "\n";
print " test - run test code\n";
print "\n";
}
# HOUSEKEEPING }}}
# MAIN {{{
# ----------------------------------------
if ( $#ARGV < 0 ) {
usage();
exit;
}
# jic
if ( ! -d $testdir ) # check if directory exists
{ `mkdir -p $testdir`; }
foreach( @ARGV ) {
if ( /all/i ) {
file_io_tests();
fork_tests();
array_tests();
hash_tests();
funcref_test();
}
elsif ( /file/i ) {
file_io_tests();
}
elsif ( /fork/i ) {
fork_tests();
}
elsif ( /array/i ) {
array_tests();
}
elsif ( /hash/i ) {
hash_tests();
}
elsif ( /func/i ) {
funcref_test();
}
elsif ( /test/i ) {
print "this is a test\n";
}
# unknown
else {
usage();
print "*** Unknown Option: [ $_ ]\n\n";
}
}
# MAIN }}}
# ----------------------------------------
# ----------------------------------------