App-Cheats
view release on metacpan or search on metacpan
perl -le 'print unpack "H08",pack "L>",2'
# Convert Big Endian to Little Endian (approach 1)
echo 0x89346512 | perl -ple 's/(\d\d)(\d\d)(\d\d)(\d\d)/$4$3$2$1/'
# Convert Big Endian to Little Endian (approach 2)
echo 0x3487 | perl -ple 's/(?:(\d\d)(\d\d))?(\d\d)(\d\d)/$4$3$2$1/'
echo 0x89346512 | perl -ple 's/(?:(\d\d)(\d\d))?(\d\d)(\d\d)/$4$3$2$1/'
#############################################################
## Perl Error Handling
#############################################################
# Perl Error Handling
# die can return more detailed info. (perl)
eval {
die {
str => "some error name",
type => "bad",
level => 2,
};
};
p $@;
# Can use $^S to check if inside of an eval block.
# eval State.
perl -E '
sub f { say $^S }
f;
eval { f };
eval "f";
'
0
1
1
#############################################################
## Perl File Test Markers
#############################################################
# Example of reading from the end of file in perl.
while (<DATA>){
$r = /start/../end/;
print if $r > 1 and $r !~ /E0$/;
}
__DATA__
junk1
start
data1
data2
data4
end
junk2
# On systems where $0 cannot be used to find out
# the file size, one can maybe still use <DATA>
# to determine the size of the file.
use POSIX qw(strftime);
$raw_time = (stat(DATA))[9];
$size = -s DATA;
$kilosize = int($size / 1024) . "k";
print "<P>Script size is $kilosize\n";
print strftime(
"<P>Last script update: %c (%Z)\n", localtime($raw_time)
);
__DATA__
DO NOT REMOVE THE PRECEDING LINE.
#############################################################
## Perl File Syntax
#############################################################
# Can use "#" as a line number directives. (Perl File Syntax)
# https://perldoc.perl.org/perlsyn#Plain-Old-Comments-(Not!)
# Note: It marks the NEXT line.
perl -E 'eval qq(# line 123 myfile.txt\ndie "My bad"); say $@'
My bad at myfile.txt line 123.
# Perl File Syntax
# When opened for reading, the special
# filename âââ refers to STDIN. When
# opened for writing, the same special
# filename refers to STDOUT.
# Normally, these are specified as â<ââ and â>ââ,
# respectively.
open(INPUT, "â" ) || die; # reâopen standard input for reading
open(INPUT, "<â") || die; # same thing, but explicit
open(OUTPUT, ">â") || die; # reâopen standard output for writing
# Can always use / for files in perl (even on DOS).
my $path = "a\b\c.txt";
my $path = "a/b/c.txt";
# Read piped output in perl.
open PIPE, "-|", "perl out.pl" or die $!;
while( my $line = <PIPE> ){
print $line;
}
close PIPE;
#############################################################
## Perl File Test Operators
#############################################################
# Check if reading from pipe or standard input STDIN keyboard
echo "abc" | perl -le 'print -t STDIN ? "STDIN" : "pipe"' # "pipe"
perl -le 'print -t STDIN ? "STDIN" : "pipe"' # "STDIN"
# Read from either PIPE or from standard input STDIN (in Perl)
perl -le 'push @ARGV, <STDIN> unless -t STDIN; print "[$_]" for @ARGV'
perl -le 'push @ARGV, <STDIN> unless -t; print "[$_]" for @ARGV'
perl -le 'push @ARGV, map /\S+/g,<STDIN> unless -t; print "[$_]" for @ARGV'
perl -le 'print -t() ? "RIGHT" : "LEFT"'
echo | perl -le 'print -t() ? "RIGHT" : "LEFT"'
#############################################################
uses: shogo82148/actions-setup-perl@v1.28.0
with:
perl-version: ${{ matrix.perl-version }}
distribution: ${{ matrix.distribution }}
- uses: actions/download-artifact@v4
with:
name: build_dir
path: .
- name: install deps using cpanm
uses: perl-actions/install-with-cpanm@v1
with:
cpanfile: "cpanfile"
args: "--with-suggests --with-recommends --with-test"
- run: prove -lr t
env:
AUTHOR_TESTING: 0
RELEASE_TESTING: 0
# Additional folder preparation (module-starter)
# Add meta files.
Build manifest
Build manifest_skip
Build distmeta
Build distcheck
# Build and run a perl distribution (module-starter)
Build.PL
Build # Can use tab completion.
Build test
RELEASE_TESTING=1 Build test
Build disttest
Build dist
#############################################################
## Perl Modules - Mojo
#############################################################
# Mojo DSL
monkey_patch $caller,
a => sub { $caller->can('any')->(@_) and return $ua->server->app },
b => \&b,
c => \&c,
d => sub { $ua->delete(@_)->result },
f => \&path,
g => sub { $ua->get(@_)->result },
h => sub { $ua->head(@_)->result },
j => \&j,
l => sub { Mojo::URL->new(@_) },
n => sub (&@) { say STDERR timestr timeit($_[1] // 1, $_[0]) },
o => sub { $ua->options(@_)->result },
p => sub { $ua->post(@_)->result },
r => \&dumper,
t => sub { $ua->patch(@_)->result },
u => sub { $ua->put(@_)->result },
x => sub { Mojo::DOM->new(@_) };
}
# Download a PDF file using Perl
# Will not download if it is already up to date. (by etag)
perl -Mojo -E "my $q=chr 34; sub get_etag($tx){ $tx->result->headers->etag =~ s/^$q|$q$//gr; } my $ua = Mojo::UserAgent->new; my $url = Mojo::URL->new('https://hop.perl.plover.com/book/pdf/HigherOrderPerl.pdf'); my $f = $url->path->parts->[-1]; my $t...
# Fetch latest unicode characters (Windows)
perl -CSAD -Mojo -mcharnames -E "my $ua = Mojo::UserAgent->new; my $url = 'https://blog.emojipedia.org/whats-new-in-unicode-10/'; my $tx = $ua->get($url); die qq(Error getting) unless $tx->result->is_success; my $d = $tx->result->dom->find('ul:not([c...
# Fetch latest unicode characters (Linux)
perl -CSAD -Mojo -mcharnames -E 'my $ua = Mojo::UserAgent->new; my $url = "https://blog.emojipedia.org/whats-new-in-unicode-10/"; my $tx = $ua->get($url); die qq(Error getting) unless $tx->result->is_success; my $d = $tx->result->dom->find("ul:not([c...
# Make the client mojo page auto reload/refresh
plugin 'AutoReload';
# Create a simple mojo server and connect to it.
perl -Mojo -E 'say a("/status" => {text => "Active!"})->start("daemon", "-l", "http://*:8088")'
perl -Mojo -E 'a("/hello" => { text => "Welcome!" } )->start' get /hello
#
perl -Mojo -E 'a("/hello" => { text => "Welcome!" } )->start' daemon
perl -Mojo -E 'say a("/hello" => {text => "Hello Mojo!"})->start("daemon")'
perl -Mojo -E 'say a("/hello" => {text => "Hello Mojo!"})->start("daemon", "-l", "http://*:8080")'
mojo get http://127.0.0.1:3000/
#
# View local files on an endpoint:
perl -Mojo -E 'say a("/" => {text => "Hello Mojo!"}); a("ls" => sub{ my @files = glob "*/*"; $_->render( json => \@files) } )->start("daemon")'
mojo get http://127.0.0.1:3000/ls
#
# Show a message on connection.
perl -Mojo -E 'a("/" => sub{ say $_->req->to_string; $_->render( text => "123") })->start' daemon
# View available routes in a mojo server
perl -Mojo -E 'a("/hello" => { text => "Welcome!" } )->start' routes
# Easily create several routes.
perl -Mojo -E 'a "/" => {text => "Main"}; a("/hello" => {text => "Hello"})->start' daemon
# Use text in a CSS selector in Mojo.
perl -Mojo -E 'my $x = x("<A><B>Text1</B></A><A><B>Text2</B></A>"); say $x->at("b:text(Text2)")'
perl -Mojo -E 'my $x = x("<A><B>Text1</B></A><A><B>Text2</B></A>"); say $x->at("a:has(b:text(Text2))")'
perl -Mojo -E 'my $x = x("<A><B>Text1</B></A><A><B>Text2</B></A>"); say $x->at("a:has(b:text(/Text2/))")'
#############################################################
## Perl Modules - Mojo::Base
#############################################################
# Create accessor methods (like Mojo::Base::attr)
sub _has {
no strict 'refs';
for my $attr ( @_ ) {
*$attr = sub {
return $_[0]{$attr} if @_ == 1; # Get: return $self-<{$attr}
$_[0]{$attr} = $_[1]; # Set: $self->{$attr} = $val
$_[0]; # return $self
};
}
}
_has qw(
path
lol
tree
class_is_path
);
#############################################################
## Perl Modules - Mojo::Promise
#############################################################
# Promise usage
perl -Mojo -E "my $p = Mojo::Promise->new; $p->then(sub($robot,$human){ say qq(robot: $robot); say qq(human: $human); }, sub{ say qq!Rejected with: @_!} )->catch( sub{say qq!Error: @_!} ); $p->resolve(qw/Bender Fry Leela/); $p->wait"
# Simple Mojo promise example
perl -MMojo::Promise -E '$p = Mojo::Promise->new; $p->then(sub{say "OK"}); $p->resolve; $p->wait'
perl -MMojo::Promise -E '$p = Mojo::Promise->new; $p->then(sub{say "OK"}, sub{say "BAD"}); $p->resolve; $p->wait'
perl -MMojo::Promise -E '$p = Mojo::Promise->new; $p->then(sub{say "OK"}, sub{say "BAD"}); $p->reject; $p->wait'
# Simple Mojo promise example - timer (OK)/ timeout (BAD)
perl -MMojo::Promise -E "$p = Mojo::Promise->new; $p->then(sub{say 'OK'}, sub{say 'BAD'}); $p->timeout(1); $p->wait"
perl -MMojo::Promise -E "$p = Mojo::Promise->new; $p->then(sub{say 'OK'}, sub{say 'BAD'}); $p->timer(1); $p->wait"
# Chain of promises - short way, but not working for the 2nd level
perl -Mojo -MMojo::Promise -E "my $p = Mojo::Promise->new; $p->then(sub{say '1-OK'}, sub{say '1-BAD'})->then(sub{say '2-OK'}, sub{say '2-BAD'}); $p->reject; $p->wait"
# Chain of promises - long way
perl -Mojo -MMojo::Promise -E "my $p = Mojo::Promise->new; my $p2; $p2 = $p->then(sub{say '1-OK'; $p2->resolve}, sub{say '1-BAD'; $p2->reject}); $p2->then(sub{say '2-OK'}, sub{say '2-BAD'}); $p->reject; $p->wait"
# Using get_p (GET with a promise)
perl -Mojo -MMojo::Promise -E "my $ua = Mojo::UserAgent->new; $ua->get_p(shift)->then(sub{say qq(1-OK: @_)}, sub{say qq(1-BAD: @_)})->wait" mojolicious.org
# Create a list of promises and a top promise to watch them all
perl -MMojo::Promise -E "@p = map { my $p = Mojo::Promise->new; my $n = $_; $p->then(sub{say $n ** 2}, sub{ warn qq(Error in $n\n)}); $p } 1..10; $tp = Mojo::Promise->all(@p)->then(sub{say 'OK'}, sub{say 'NOK'}); $_->resolve for @p; $tp->wait"
#
# Reject a promise
perl -MMojo::Promise -E "@p = map { my $p = Mojo::Promise->new; my $n = $_; $p->then(sub{say $n ** 2}, sub{ warn qq(Error in $n\n)}); $p } 0..10; $tp = Mojo::Promise->all(@p)->then(sub{say 'OK'}, sub{say 'NOK'}); $p[4]->reject; $tp->wait"
#
# Try rejecting/approving
perl -Mojo -MMojo::Promise -E "my @p = map {my $n = $_; my $p = Mojo::Promise->new; $p->then(sub{say qq(P-OK: $n)}, sub{say qq(P-BAD: $n) }); $p } 0..2; my $hop = Mojo::Promise->all(@p)->then(sub{say 'OK'}, sub{say 'BAD'}); $p[$_]->reject for 0,1,2; ...
# Mojo promise race - first one wins
perl -MMojo::Promise -E "@p = map { my $p = Mojo::Promise->new; my $n = $_; $p->then(sub{say $n ** 2}, sub{ warn qq(Error in $n\n)}); $p } 0..10; $race = Mojo::Promise->race(@p)->then(sub{say 'OK'}, sub{say 'NOK'}); $_->resolve for $p[4], @p; $race->...
# HigherOrder Promises
perl -Mojo -MMojo::Promise -E "my @p = map {Mojo::Promise->new} 1..3; my $hop = Mojo::Promise->new; $hop->all(@p)->then(sub{say qq(OK: @_)}, sub{say qq(BAD: @_)}); $hop->wait"
#
# Mojo::Promise::Role::HigherOrder - Not working
perl -MMojo::Promise -E "my @p = map {Mojo::Promise->new} 0..2; my $hop = Mojo::Promise->with_roles('+Any')->any(@p)->then(sub{say 'OK'}, sub{say 'BAD'}); $p[$_]->reject for 0,1,2; $_->resolve for @p; $hop->wait"
perl -MMojo::Promise -E "my @p = map {my $n = $_; my $p = Mojo::Promise->new; $p->then(sub{say qq(\nP-OK$n)}, sub{say qq(\nP-BAD$n) }); $p } 0..2; my $hop = Mojo::Promise->with_roles('+Any')->any(@p)->then(sub{say 'OK'}, sub{say qq(\nBAD)}); $p[$_]->...
# Check if a[href] urls in html files are accessbile
for file in *.xhtml; do echo; echo $file; my_get_ok $(perl -Mojo -E 'my $dom = x f(shift)->slurp; say for $dom->find("a[href]")->map("attr", "href")->each' "$file" | not -r '^\w+\.\w+$' | sort -u); done
my_html_links_check *.xhtml
#############################################################
## Perl Modules - Mojo::UserAgent
#############################################################
# Download a PDF file using Perl
perl -Mojo -E "my $ua = Mojo::UserAgent->new; my $url = Mojo::URL->new('https://hop.perl.plover.com/book/pdf/HigherOrderPerl.pdf'); my $f = $url->path->parts->[-1]; my $tx = $ua->get($url)->result->save_to($f)"
# Download a PDF file using Perl
# Will not download if it is already up to date. (by date)
perl -Mojo -E "my $ua = Mojo::UserAgent->new; my $url = Mojo::URL->new('https://hop.perl.plover.com/book/pdf/HigherOrderPerl.pdf'); my $f = $url->path->parts->[-1]; my $t = (stat($f))[9]; my $d = Mojo::Date->new($t); my $tx = $ua->get($url, {'If-Modi...
# Create a Mojo Websocket and message hooks
perl -Mojo -E "my $ua = Mojo::UserAgent->new; say r $ua->websocket_p('ws://172.17.17.1:80/get_jobs')->then(sub($tx){ my $p = Mojo::Promise->new; $tx->on(finish => sub($tx,$code,$reason){ say qq(Closed with code $code); $p->resolve;}); $tx->on(message...
# Show all the redirects
perl -Mojo -E "my @txs = Mojo::UserAgent->new->max_redirects(10)->head(shift); while(my $tx = $txs[0]->previous){ unshift @txs, $tx } say $_->req->url for @txs" mojolicious.org
perl -Mojo -E "my $tx = Mojo::UserAgent->new->max_redirects(10)->head(shift); say $_->req->url for $tx->redirects->@*, $tx" mojolicious.org
#############################################################
## Perl Modules - Mojo::Util
#############################################################
# steady_time and promises
perl -Mojo -MMojo::Util=steady_time -E "sub st($m){printf qq(%-20s: %s\n), steady_time, $m} st('Before'); my $ua = Mojo::UserAgent->new; for my $url(@ARGV){ st(qq(Trying: $url)); state $cnt = 0; my $label = $cnt++; $ua->get($url => sub{ st(qq(Finishe...
#############################################################
## Perl Modules - Mojolicious::Lite
#############################################################
# Mojolicious::Lite simple server example.
+ #!/usr/bin/env perl
+
+ use Mojolicious::Lite -signatures;
+ use Mojo::File qw( path );
+
+ my $file = "story/text.txt";
+
+ get "/" => { text => "REV 1" };
+ get "/page2" => { text => "Page2" };
+ get "/error" => sub { exit 1 };
+
+ get "/story" => sub ($c) {
+ $c->render( json => { story => path($file)->slurp } );
+ };
+ post "/story" => sub ($c) {
+ path($file)->spurt( $c->req->json->{text} );
+ $c->render( text => "Saved!" );
+ };
+
+ app->start("daemon");
#############################################################
## Perl Modules - Mojolicious::Plugin::Directory
#############################################################
# Similar to python's simple http server
python -m SimpleHTTPServer 8080
#
cpanm Mojolicious::Plugin::Directory
perl -Mojo -MCwd=getcwd -E 'a->plugin("Directory", root => getcwd())->start' daemon
#############################################################
## Perl Modules - Moose
#############################################################
# Override a method that is defined in a role (Moose)
## Python Virtual Environment
#############################################################
# Virtual environment in python (requirements.txt)
#
# Install as admin
pip install virtualenv
#
# Create environment folder
python -m venv env
#
# Activate it
env\Scripts\activate
#
# Install packages
python -m pip install --upgrade pip
pip install bottle
#
# Save requirements.txt
pip freeze > requirements.txt
#
# Save downloaded files locally
mkdir sdist
cd sdist
pip download -r ..\requirements.txt
#
# Close environment
deactivate
#
# Install requirements somewhere else
pip install -r requirements.txt --find-links sdist --no-index
#############################################################
## Python Modules - bottle
#############################################################
# Python bottle module routing options
self.app.get("/<f:path>")(lambda f: bottle.static_file(f, root=path))
self.app.get("/<file:path>")(lambda file: self.get_static_file(file,path))
#
def get_static_file(self,file,path):
self.logger.debug("get_static_file(file:{},path={})".format(file,path))
# Remove option timestamp/UID: version--UID--123.js
file = re.sub(self.is_uid,'',file)
return bottle.static_file(file, root=path)
#
#
The following filters are implemented by default and more may be added:
:int matches (signed) digits only and converts the value to integer.
:float similar to :int but for decimal numbers.
:path matches all characters including the slash character in a non-greedy way and can be used to match more than one path segment.
:re allows you to specify a custom regular expression in the config field. The matched value is not modified.
#############################################################
## Python Modules - datetime
#############################################################
# Get yyyymmmdd format in Python from a integer Epoch string
python -c "import datetime; import os; s=os.stat('version.js'); t=datetime.datetime.fromtimestamp(int(s.st_mtime)).strftime('%Y%m%d%H%M%S'); print(t)"
20210203102701
# Print current time in about YYYYMMDD
python -c "import datetime; print(datetime.date.today().strftime('%Y%m%d'))"
# Current timestamp as a string
python -c "from datetime import datetime; print(datetime.now(tz=None))"
#############################################################
## Python Modules - gevent
#############################################################
# Using gevent in a python webserver
#
import gevent.pywsgi
import geventwebsocket
import geventwebsocket.handler
class Server:
def __init__(self,...):
self.server = gevent.pywsgi.WSGIServer((address, port), self.app,
handler_class=geventwebsocket.handler.WebSocketHandler)
#############################################################
## Python Modules - json
#############################################################
# Using json in a python webserver
#
import json
class Server:
def info(self):
try:
return json.dumps(possible_endpoints)
except KeyError:
return bottle.HTTPError(404, "Error occurred")
#############################################################
## Python Modules - logging
#############################################################
# Log format to use for the logger
log_format = '%(asctime)s %(levelname)s %(module)s.%(funcName)s:%(lineno)d %(message)s'
# Using rotating logs in python (at midnight the log file changes)
import logging.handlers
file_handler = logging.handlers.TimedRotatingFileHandler(filename=log_file, when="midnight")
#############################################################
## Python Modules - os
#############################################################
# Python get the current working directory (dirname)
this_dir = os.path.dirname(os.path.realpath(__file__))
# Example of using system command in python.
python3 -c 'import os; os.system(" ".join(["which", "mid2agb"]))'
( run in 1.703 second using v1.01-cache-2.11-cpan-5b529ec07f3 )