App-Cheats

 view release on metacpan or  search on metacpan

cheats.txt  view on Meta::CPAN

    };
    say "\nreverted";
    ABC->func
'

# Sub::Override way to temporarily replace a function (symbol table, typeglob)
# Also gets the orignal sub name.
perl -MSub::Override -E '
    {
        package ABC;
        sub func{ say "func" }
    }
    for (1..3) {
        my $sub;
        $sub = Sub::Override->new( "ABC::func" => sub {
            say "pre";
            $sub->{"ABC::func"}->();
            say "post";
        });
        ABC->func;
    };
    say "\nreverted";
    ABC->func
'

# Override a function in perl.
perl -E '
    package P;
    my $Obj = bless {}, "P";
    my $Class = ref $Obj;
    *{"${Class}::RunMe"} = sub { say "hello world" };
    P::RunMe();
    $Obj->RunMe();
'

# For loop makes an alias of each element.
# Changes to the alias also change the element.
perl -E 'my $v = 111; $_ = 222 for $v; say $v'
222
#
# Similar way to make an alias to a variable.
perl -E 'my $v = 111; { local *_ = \$v; $_ = 222 } say $v'
222

# Perl Symbol Table
# Stash - hash like structure describing all
# package variables
%main::
%My_Package::

# Perl Symbol Table
# Type glob magic - only the type gets modified.
*foo = \$scalar; 
*foo = \@array;


#############################################################
## Perl Unicode - General
#############################################################

# Create invalid Malformed UTF-8 character (unicode)
perl -C -Me -MEncode -E 'my $v = "a\372z"; dd $v; Encode::_utf8_on($v); say ""; dd $v; say $v'

# Check if valid utf8 (unicode)
Encode::is_utf8( $Param{Text}, 1 )
utf8::valid( $Param{Text} )

# Pick a unicode character at a time.
perl -Mutf8 -C -E 'say for "äö" =~ /(\X)/g'
ä
ö
perl -Mutf8 -C -E 'say for "äö" =~ /(.)/g'
ä
ö


#############################################################
## Perl Unicode - Codes
#############################################################

# Unicode salute/saluting.
perl -C -E 'say "\x{1FAE1}"'
🫡
# Draw a box with unicode in perl.
perl -C -E 'say "\N{BOX DRAWINGS LIGHT ARC DOWN AND RIGHT}" . ("\N{BOX DRAWINGS LIGHT HORIZONTAL}" x 5) . "\N{BOX DRAWINGS LIGHT ARC DOWN AND LEFT}"; say "\N{BOX DRAWINGS LIGHT VERTICAL}     \N{BOX DRAWINGS LIGHT VERTICAL}" for 1..2; say "\N{BOX DRAW...

# Unicode error codes:
➜ HEAVY ROUND-TIPPED RIGHTWARDS ARROW U+279c 0x279c 10140 023634
✖ HEAVY MULTIPLICATION X              U+2716 0x2716 10006 023426

# Unicode star
★ BLACK STAR U+2605 0x2605 9733 023005


#############################################################
## Perl Unicode - Mojibake
#############################################################

# Perl mojibake guide.
https://dev.to/drhyde/a-brief-guide-to-perl-character-encoding-if7

# Perl mojibake examples. (wrong length)
perl -E '$s = "é"; say $s . " contains " . length($s) . " chars"'
é contains 2 chars

# Perl mojibake examples. (utf8 is not enough)
perl -Mutf8 -E '$s = "é"; say $s . " contains " . length($s) . " chars"'
� contains 1 chars

# Perl mojibake examples. (-C or binmode to get correct encoding and therefore length)
perl -Mutf8 -E 'binmode(STDOUT, ":encoding(UTF-8)"); $s = "é"; say $s . " contains " . length($s) . " chars"'
perl -Mutf8 -C -E '$s = "é"; say $s . " contains " . length($s) . " chars"'
perl -Mutf8 -C -E 'binmode(STDOUT, ":encoding(UTF-8)"); $s = "é"; say $s . " contains " . length($s) . " chars"'
é contains 1 chars

# Perl mojibake examples. (Simulate malformed UTF-8 character warnings)
echo '"key": "é"' > my.out
iconv -f utf-8 -t latin1 my.out > my2.out
file my*.out
cat my*
    "key": "�"
    "key": "é"
cat my2.out | perl -Mutf8 -C -lne '/\d/'
cat my2.out | perl -C -lne '/\d/'
    Malformed UTF-8 character: \xe9\x22 (too short; 2 bytes available, need 3) in pattern match (m//) at -e line 1, <> line 1.
    Malformed UTF-8 character: \xe9\x22 (unexpected non-continuation byte 0x22, immediately after start byte 0xe9; need 3 bytes, got 1) in pattern match (m//) at -e line 1, <> line 1.
cat my2.out | perl -Mutf8 -C -ne '/\d/'
cat my2.out | perl -C -ne '/\d/'
perl -C -ne '/\d/' < my2.out
perl -CI -ne '/\d/' < my2.out
perl -ne 'INIT{binmode STDIN, ":utf8"} /\d/; print' < my2.out
    Malformed UTF-8 character: \xe9\x22\x0a (unexpected non-continuation byte 0x22, immediately after start byte 0xe9; need 3 bytes, got 1) in pattern match (m//) at -e line 1, <> line 1.
perl -ne 'INIT{binmode STDIN, ":encoding(UTF-8)"} /\d/; print' < my2.out
    "key": "\xE9"
perl -C -lne 'print utf8::valid($_) ? "valid" : "invalid"' < my.out
    valid
perl -C -lne 'print utf8::valid($_) ? "valid" : "invalid"' < my2.out
    invalid
#
# Summary:
    - A file/string may be declared as utf8, but it really is not.
    - "-CI" is the same as 'binmode STDIN, ":utf8"'
    - ":encoding(UTF-8)" should be preferred over ":utf8"
    - Use "utf8::valid" to check for malformed strings.

# iconv using perl (piconv)
# Saves a file using wrong encoding (mojibake)
perl -CA -le 'open OUT, ">:encoding(latin1)", "my3.out" or die $!; print OUT shift' '"key": "é",'

# Find non ascii characters.
perl -C -lne 'print $1 if /([^[:ascii:]])/' my.yml
uni_convert --string "$(perl -C -lne 'print $1 if /([^[:ascii:]])/' my.csv)"
echo 'aböc' | perl -nE 'say "[$1]" if /(\P{ASCII}+)/'


#############################################################
## Perl Unicode - Encode/Decode
#############################################################

# Compare use of encode/decode.
# Start with non unicode.
perl -C -MEncode -Mutf8 -C -Me -e '$_ = "\xef\xac\xa1"; my $en = eval{encode("UTF-8", $_)} // ""; my $de = eval{decode("UTF-8", $_)} // ""; say; say $en; say $de; dd $_; dd $en, dd $de'
ﬡ
ﬡ
ﬡ
SV = PV(0xb40000740302de60) at 0xb4000074030a9be8
  REFCNT = 1
  FLAGS = (POK,IsCOW,pPOK)
  PV = 0xb400007382ce28a0 "\xEF\xAC\xA1"\0
  CUR = 3
  LEN = 16
  COW_REFCNT = 1
SV = PV(0xb40000740302e0d0) at 0xb4000074030a93a8
  REFCNT = 1
  FLAGS = (POK,pPOK,UTF8)
  PV = 0xb4000074031623d0 "\xEF\xAC\xA1"\0 [UTF8 "\x{fb21}"]
  CUR = 3
  LEN = 16
SV = PV(0xb40000740302dea0) at 0xb40000740301f930
  REFCNT = 1
  FLAGS = (POK,pPOK)
  PV = 0xb400007382ce2d70 "\xC3\xAF\xC2\xAC\xC2\xA1"\0
  CUR = 6
  LEN = 16

# Compare use of encode/decode.
# Start with unicode.
perl -C -MEncode -Mutf8 -C -Me -e '$_ = "\x{fb21}"; my $en = eval{encode("UTF-8", $_)} // ""; my $de = eval{decode("UTF-8", $_)} // ""; say; say $en; say $de; dd $_; dd $en, dd $de'
ﬡ
ﬡ
SV = PV(0xb40000721e02de60) at 0xb40000721e0a2be8
  REFCNT = 1
  FLAGS = (POK,IsCOW,pPOK,UTF8)
  PV = 0xb40000719dce28a0 "\xEF\xAC\xA1"\0 [UTF8 "\x{fb21}"]
  CUR = 3
  LEN = 16
  COW_REFCNT = 1
SV = PV(0xb40000721e034590) at 0xb40000721e0a23a8
  REFCNT = 1
  FLAGS = (POK,IsCOW,pPOK)
  PV = 0xb40000721e02c0c0 ""\0
  CUR = 0
  LEN = 16
  COW_REFCNT = 1
SV = PV(0xb40000721e02dea0) at 0xb40000721e01f930
  REFCNT = 1
  FLAGS = (POK,pPOK)
  PV = 0xb40000719dce2d70 "\xEF\xAC\xA1"\0
  CUR = 3
  LEN = 16

# Compare use of encode/decode.
# Start with name (must be upper case).
perl -C -MEncode -Mutf8 -C -Me -e '$_ = "\N{HEBREW LETTER ALEF}"; my $en = eval{encode("UTF-8", $_)} // ""; my $de = eval{decode("UTF-8", $_)} // ""; say; say $en; say $de; dd $_; dd $en, dd $de'
א
×
SV = PV(0xb400007267a2de60) at 0xb400007267aa0be8
  REFCNT = 1
  FLAGS = (POK,IsCOW,pPOK,UTF8)
  PV = 0xb400007267a2c0c0 "\xD7\x90"\0 [UTF8 "\x{5d0}"]
  CUR = 2
  LEN = 16
  COW_REFCNT = 1
SV = PV(0xb400007267a2e0b0) at 0xb400007267a1f948
  REFCNT = 1
  FLAGS = (POK,IsCOW,pPOK)
  PV = 0xb4000071e76df8b0 ""\0
  CUR = 0
  LEN = 16
  COW_REFCNT = 1
SV = PV(0xb400007267a2dea0) at 0xb400007267a1f930
  REFCNT = 1
  FLAGS = (POK,pPOK)
  PV = 0xb4000071e774e170 "\xD7\x90"\0
  CUR = 2
  LEN = 16

# Display ALEF from different ways.
perl -C -E 'say "\N{HEBREW LETTER ALEF}"'   א
perl -C -E 'say "\N{U+5d0}"'                א
perl -C -E 'say "\x{5d0}"'                  א
perl -C -E 'say chr(0x5d0)'                 א
perl -C -E 'say chr(0x05d0)'                א
perl -C -E 'say chr(1488)'                  א
perl -C -E 'say v1488'                      א

# To and from Unicode code point and unnicode byte stream.

cheats.txt  view on Meta::CPAN

# (Perl Modules - AnyEvent)
# NOT WORKING!
perl -MAnyEvent -E 'my @files = (1..30); my $cv = AnyEvent->condvar; foreach my $file (@files) { $cv->begin; AnyEvent->timer(after => 0, cb => sub { say "Processing file $file"; sleep(1); $cv->end; }); } $cv->recv;'


#############################################################
## Perl Modules - Automake::Config
#############################################################

# Install Automake::Config (termux)
git clone git@github.com:poti1/arm-none-eabi.git
cd arm-none-eabi
cpanm --look automake-1.15.gz
$ ./configure
$ make
$ make install


#############################################################
## Perl Modules - autovivification
#############################################################

# autovivification Example:
perl -Me -E 'my $h = { k => 11  }; no autovivification; say defined $h->{k2}{k3}{k5}; p $h'
{
    k   11
}


#############################################################
## Perl Modules - B::Concise
#############################################################

# Perl Modules - B::Concise
# explain what a perl program is doing (very concise).
perl -MO=Concise -e 'print 111'


#############################################################
## Perl Modules - B::Deparse
#############################################################

# Perl Modules - B::Deparse
# explain what a perl program is doing (simply)
perl -MO=Deparse -e 'print 111'


#############################################################
## Perl Modules - bignum
#############################################################

# Convert big numbers into full form
# from scientific notation to expanded form
echo "$b" | perl -Mbignum -lpe '$_ += 0'


#############################################################
## Perl Modules - binmode
#############################################################

# Using unicode in perl STDOUT
perl -CO   script
perl -C    script # Which is same as
perl -CDSL script # S includes I/O
perl -e 'binmode STDOUT, "encoding(UTF-8)"'
perl -e 'binmode STDOUT, ":utf8"'
perl -E 'use open qw/:std :utf8/; say "\N{SNOWFLAKE}"'

# Mixed up encoding.
perl -E '$s = "é"; say length($s) . " $s"'
2 é
perl -C -E '$s = "é"; say length($s) . " $s"'
2 é
perl -Mutf8 -E '$s = "é"; say length($s) . " $s"'
1 �
perl -C -Mutf8 -E '$s = "é"; say length($s) . " $s"'
1 é


#############################################################
## Perl Modules - Business::CreditCard
#############################################################

# Validate a credit card number.
perl -MBusiness::CreditCard -E 'say validate("5276 4400 6542 1319")'
1
#
perl -MBusiness::CreditCard -E 'say cardtype("5276 4400 6542 1319")'
MasterCard


#############################################################
## Perl Modules - charnames
#############################################################

# Convert between a Unicode character, hexidecimal number and the name
perl -CDAS -E 'use charnames(); printf "%s %#x %s\n", $_, ord, charnames::viacode(ord) for @ARGV' ❄ ☃
# ❄ 0x2744 SNOWFLAKE
# ☃ 0x2603 SNOWMAN

# Converting between a Unicode name, code, and string
# Name: SNOWFLAKE
# Code: 0x2744, 10052
# String: \N{SNOWFLAKE}, \N{U+2744}, \x{2744}, ❄
#
perl -C -E 'say "\N{SNOWFLAKE}"'                                                 # \N{SNOWFLAKE} -> ❄
perl -C -E 'say "\N{U+2744}"'                                                    # \N{U+2744}    -> ❄
perl -C -E 'say "\x{2744}"'                                                      # \x{2744}      -> ❄
perl -C -Mutf8 -E 'say "❄"'                                                      # ❄             -> ❄
perl -E 'say "❄"'                                                                # ❄             -> ❄
perl -E 'use open qw/:std :utf8/; say "\N{SNOWFLAKE}"'                           # \N{SNOWFLAKE} -> ❄
#
perl -Mutf8 -E 'printf "%#x\n", ord "❄"'                                         # ❄             -> 0x2744
perl -Mutf8 -E 'say ord "❄"'                                                     # ❄             -> 10052
perl -Mutf8 -Mcharnames=:full -E 'say charnames::viacode ord "❄"'                # ❄             -> SNOWFLAKE
#
perl -C -Mcharnames=:full -E 'say charnames::vianame("SNOWFLAKE")'               # SNOWFLAKE     -> 2744
perl -C -Mcharnames=:full -E 'printf "%#x\n", charnames::vianame("SNOWFLAKE")'   # SNOWFLAKE     -> 0x2744
perl -C -Mcharnames=:full -E 'say charnames::string_vianame("SNOWFLAKE")'        # SNOWFLAKE     -> ❄
#
perl -C -Mcharnames=:full -E 'say charnames::viacode("U+2744")'                  # U+2744        -> SNOWFLAKE
perl -C -Mcharnames=:full -E 'say charnames::viacode(0x2744)'                    # 0x2744        -> SNOWFLAKE
perl -C -Mcharnames=:full -E 'say charnames::viacode("10052")'                   # 10052         -> SNOWFLAKE

# Difference between the different whitespace regex characters
perl -Mcharnames=:full -E 'my @qr = (qr/\s/, qr/\h/, qr/\v/, qr/[[:space:]]/, qr/\p{Space}/); my $fmt = "%#06x" . ("%2s" x @qr) . " %s\n"; printf "\nVersion: $^V\n$fmt\n", qw/- s h v p u Name/; for my $ord (0..0x10ffff){ my $chr = chr $ord; next unle...
#
# s - \s
# v - \v
# p - [[:space:]] (POSIX)
# u - \p{Space}
# Version: v5.32.1
# 000000 s h v p u Name
#
# 0x0009 x x   x x CHARACTER TABULATION
# 0x000a x   x x x LINE FEED
# 0x000b x   x x x LINE TABULATION
# 0x000c x   x x x FORM FEED
# 0x000d x   x x x CARRIAGE RETURN
# 0x0020 x x   x x SPACE
# 0x0085 x   x x x NEXT LINE
# 0x00a0 x x   x x NO-BREAK SPACE
# 0x1680 x x   x x OGHAM SPACE MARK
# 0x2000 x x   x x EN QUAD
# 0x2001 x x   x x EM QUAD
# 0x2002 x x   x x EN SPACE
# 0x2003 x x   x x EM SPACE
# 0x2004 x x   x x THREE-PER-EM SPACE
# 0x2005 x x   x x FOUR-PER-EM SPACE
# 0x2006 x x   x x SIX-PER-EM SPACE
# 0x2007 x x   x x FIGURE SPACE
# 0x2008 x x   x x PUNCTUATION SPACE
# 0x2009 x x   x x THIN SPACE
# 0x200a x x   x x HAIR SPACE
# 0x2028 x   x x x LINE SEPARATOR
# 0x2029 x   x x x PARAGRAPH SEPARATOR
# 0x202f x x   x x NARROW NO-BREAK SPACE
# 0x205f x x   x x MEDIUM MATHEMATICAL SPACE
# 0x3000 x x   x x IDEOGRAPHIC SPACE

# Last unicode character
0x10FFFF


#############################################################
## Perl Modules - constant
#############################################################

# Create a constant in perl.
perl -E 'use constant ABC => 123; say ABC'  123
perl -Mconstant=ABC,123 -E 'say ABC'        123
perl -E 'sub ABC(){ 123 } say ABC'          123
perl -E 'sub ABC{ 123 } say ABC'            123


#############################################################
## Perl Modules - cpanm
#############################################################

# Install cpanm
cpan App::cpanminus

# Install dependencies using cpanm
# Create file: cpanfile
requires 'Mojolicious';
recommends 'JSON::XS';
#
# Install perl dependencies from cpanfile:
cpanm --installdeps .

# Install a perl module as root
cpanm -S Selenium::Remote::Driver
cpanm --sudo Selenium::Remote::Driver


#############################################################
## Perl Modules - cpan-outdated
#############################################################

# Update outdated perl modules
cpanm App::cpanoutdated
cpan-outdated | cpanm


#############################################################
## Perl Modules - perltidy
#############################################################

# Clean up perl script
perltidy my_file

# Perltidy configuration file
vi .perltidyrc
-mbl=2 -pt=0 -b -bext='/' -blbs=1 -bom -bbb -nbl

# Tell perltidy to ignore a line
<STDIN>;    ## no critic

# html
sudo apt-get install tidy
sudo apt-get install libhtml-tidy-perl    # Perl library

cheats.txt  view on Meta::CPAN

          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::ByeStream
#############################################################

# Perl Modules - Mojo::ByeStream

cheats.txt  view on Meta::CPAN

+
+
+ 1

# Subs::Trace use case (example)
perl -I. -E '{ package P; use Subs::Trace; sub F1{10} sub F2{20} } say P::F1() + P::F2()'

# Subs::Trace cpan modules.
cpanm Subs::Trace
perl -E '{ package P; sub F1{10} sub F2{20} sub F4{40} use Subs::Trace; sub F3{30} } say P::F1() + P::F2() + P::F3() + P::F4()'
-> P::F1
-> P::F2
-> P::F4
100


#############################################################
## Perl Modules - Template (Toolkit,tt)
#############################################################

# Concatenation operator in template tookkit (tt)
Data.var1 _ Data.var2

# Compare |html and |uri:
perl -MTemplate -E 'my $out; Template->new->process( \("[% id | html %]"), { id => "has & and spaces" }, \$out); say $out'
has &amp; and spaces
#
perl -MTemplate -E 'my $out; Template->new->process( \("[% id | uri %]"), { id => "has & and spaces" }, \$out); say $out'
has%20%26%20and%20spaces


#############################################################
## Perl Modules - Term::Animation
#############################################################

# Using a terminal animation framework
perl -MTerm::Animation -MCurses -E 'use v5.32; my $anim = Term::Animation->new; halfdelay(2); $anim->new_entity(shape => "<=0=>", position => [3,7,10], callback_args => [1,0,0,0], wrap => 1); while(1){ $anim->animate; my $in = getch(); last if $in eq...

# Using a terminal animation framework (with colors)
perl -MTerm::Animation -MCurses -E 'use v5.32; my $anim = Term::Animation->new; halfdelay(1); $anim->color(1); $anim->new_entity(shape => "<=0=>", position => [3,7,10], callback_args => [1,0,0,0], wrap => 1, default_color => "yellow"); while(1){ $ani...


#############################################################
## Perl Modules - Term::ANSIColor
#############################################################

# Proper way to color text in perl instead of hardcoding
# escape codes (which are not all the same on all devices).
perl -MTerm::ANSIColor -E 'say colored ($_,$_) for qw( RED YELLOW GREEN ON_BRIGHT_BLACK )'

# Color an remote color (uncolor).
perl -MTerm::ANSIColor=colored,colorstrip -E 'say length colorstrip(colored("HEY", "YELLOW"))'
3


#############################################################
## Perl Modules - Term::ProgressBar
#############################################################

# Progress bar example 1
perl -Mojo -MTerm::ProgressBar -CO -E "STDOUT->autoflush(1); my $ua = Mojo::UserAgent->new; $ua->on(prepare => sub($ua,$tx){ my($len,$bar); $tx->res->on(progress => sub($res){ return unless $len ||= $res->headers->content_length; my $prog = $res->con...

# Progress Bar example 2
perl -MTerm::ProgressBar -E "$|++; @a=1..100; $bar = Term::ProgressBar->new({count => ~~@a}); $bar->update($_), select undef,undef,undef,0.05 for @a"
GetTerminalSize
# Progress Bar in Perl (more features shown here)
perl -MTerm::ProgressBar -E "$|++; $max=100_000; $progress = Term::ProgressBar->new({count => $max, name => 'File-1', term_width => 50, remove => 1}); $progress->minor(0); my $next_update = 0; for (0..$max){ my $is_power = 0; for (my $i = 0; 2**$i <=...


#############################################################
## Perl Modules - Term::ReadKey
#############################################################

# Get terminal width in perl
perl -MTerm::ReadKey= -E "my ($w) = GetTerminalSize(); say $w"

# Read input from the keyword/user without showing the password
perl -MTerm::ReadKey -le 'ReadMode(2); $pass .= $key while(ord($key = ReadKey(0)) !~ /^(?: 10|13 )$/x); ReadMode(0); print "Got [$pass]"'

# Read input from the keyword/user without showing the password (same, but using keywords)
perl -MTerm::ReadKey -le 'ReadMode(noecho); $pass .= $key while(ord($key = ReadKey(0)) !~ /^(?: 10|13 )$/x); ReadMode(restore); print "Got [$pass]"'
perl -MTerm::ReadKey -e 'ReadMode(2); while($c=ReadKey(0), ord($c) !~ /^(?:10|13)$/x){ $pass .= $c  } ReadMode(0); print "[$pass]\n"'

# Read input from the keyword/user without showing the password (same, but more compact)
perl -MTerm::ReadKey -le 'ReadMode(2); $pass = ReadLine(0); chomp $pass; ReadMode(0); print "Got [$pass]"'
perl -MTerm::ReadKey -le 'ReadMode(2); $_ = ReadLine(0); chomp; ReadMode(0); print "[$_]"'

# Read input from the keyword/user without showing the password (same, but on windows)
perl -MTerm::ReadKey -le "ReadMode 2; $pass = ReadLine 0; chomp $pass; ReadMode 0; print qq([$pass])"

# Read input from the keyword/user without showing the password. replace characters with a star "*"
perl -MTerm::ReadKey -e 'ReadMode(4); while($c=ReadKey(0),$o=ord($c),$o != 10 and $o != 13){ if($o == 127 || $o == 8){chop $p; print "\b \b"}elsif($o < 32){}else{ $p .= $c; print "*" }} ReadMode(0); print "[$p]\n"'
perl -MTerm::ReadKey -e 'ReadMode 3; while($c=ReadKey(0),$o=ord($c),$o != 10 and $o != 13){ if($o == 127 || $o == 8){chop $p; print "\b \b"}elsif($o < 32){}else{ $p .= $c; print "*" }} ReadMode 0; print "[$p]\n"'
perl -MTerm::ReadKey -e 'ReadMode 4; while($c=ReadKey(0),$o=ord($c),$o!=10){ if($o==127 or $o==8){chop $p; print "\b \b"}elsif($o < 32){}else{$p.=$c; print "*"}} ReadMode 0; print "[$p]\n"'


#############################################################
## Perl Modules - Term::ReadLine::Gnu
#############################################################

# Given input, return the possible completion words.
# Like compgen.
compgen -W "cat cake bat bake" -- c
perl -MTerm::ReadLine -E 'my $term = Term::ReadLine->new("my"); my $attribs = $term->Attribs; $attribs->{completion_word} = [qw( cat cake bat bake )]; my @matches = $term->completion_matches( shift//"", $attribs->{list_completion_function} ); $term->...


#############################################################
## Perl Modules - Text::CSV
#############################################################

# Write a csv file (super easy)
perl -MText::CSV_XS=csv -E "csv(in => [[qw/A B C/],[1,2,3]], out => 'my.csv')"

# Read certain lines of a CSV file
perl -l -MText::CSV -e '$csv=Text::CSV->new; open FH, "book1.csv"; while($a=$csv->getline(FH)){print $a->[0]}'

# CSV file into an array (Mike)
perl -l -MText::CSV_XS -e '$csv=Text::CSV_XS->new; open FH, "a.csv"; $a=$csv->getline_all(FH); print $a->[1][3]'


#############################################################

cheats.txt  view on Meta::CPAN

# ROText Example (Ptk,Appendix B)

# Scale Example (Ptk,Appendix B)

# Table Example (Ptk,Appendix B)

# Text Example (Ptk,Appendix B)

# TextUndo Example (Ptk,Appendix B)

# Tiler Example (Ptk,Appendix B)

# TList Example (Ptk,Appendix B)

# TopLevel Example (Ptk,Appendix B)

# Tree Example (Ptk,Appendix B)


#############################################################
## Perl Modules - Tk::TextString, Tk::TextStrings
#############################################################

# Tie Text widget to store input as an entry or label would in "-variable" (PTk)
perl -MTk -le '{package P; sub TIESCALAR{my($c,$o)=@_; bless \$o,$c} sub FETCH{my($s)=@_; $$s->get("1.0", "end")} sub STORE{my($s,$v)=@_; $$s->delete("1.0", "end"); $$s->insert("end", $v)} } $mw=MainWindow->new; $t=$mw->Text->pack; tie $v, "P", $t; $...

# Tie Text widget to -variable. Set value with button or entry (PTk)
perl -MTk -le '{package P; sub TIESCALAR{my($c,$o)=@_; bless \$o,$c} sub FETCH{my($s)=@_; $$s->get("1.0", "end")} sub STORE{my($s,$v)=@_; $$s->delete("1.0", "end"); $$s->insert("end", $v)} } $mw=MainWindow->new; $t=$mw->Text->pack; tie $v, "P", $t; $...

# Example of new TextString Mega-Widget (PTk,tie,user module)
perl -MTk -MTk::TextString -w -le '$mw=MainWindow->new; $mw->TextString(-variable => \$v)->pack; $mw->Entry(-textvariable => \$v)->pack(-side => "left"); $mw->Button(-command => sub{print "[$v]"})->pack(-side => "left"); MainLoop'

# Scolled multiple text boxes through multiple -variables (PTk,tie,user module)
perl -MTk -MTk::TextString -w -le '%d=qw(-side left); $mw=MainWindow->new; @f=map{$mw->Frame->pack} 1..3; @t=map{my $v; $f[0]->TextString(-height => 2, -variable => \$v)->pack(%d); \$v} @f; $f[1]->Entry(-textvariable => $_)->pack(%d) for @t; $f[2]->B...

# Scolled multiple text boxes through single -variable (PTk,tie,user module)
perl -MTk -MTk::TextStrings -w -le '%d=qw(-side left); $mw=MainWindow->new; @f=map{$mw->Frame->pack} 1..3; @t=map{$f[0]->TextStrings(-height => 2, -variable => \$v)->pack(%d); \$v} @f; $f[1]->Entry(-textvariable => $_)->pack(%d) for @t; $f[2]->Button...

# Can text widget and entry widget are synced (PTk, tie,user module)
perl -MTk -MTk::TextStrings -le '$mw=MainWindow->new; $mw->TextStrings(-height => 2, -variable => \$v)->pack; $mw->Entry(-textvariable => \$v)->pack; MainLoop'


#############################################################
## Perl Modules - Try::Tiny
#############################################################

# Simple approach to catching errors
# Try Catch return are subroutine based. Below return unexpectedly (at first) "BBB"
# WARNING: It has issues. Unpredictable syntax
perl -MTry::Tiny -lE 'sub try_me{ try{1/0}catch{say "Caught [$@]"; return "AAA"}; return "BBB" } $v=try_me; say $v'

# A better try/catch approach (only on lnxbr42)
# WARNING: It has issues. Highly dependent upon Perl changes
perl -MTryCatch -lE 'sub try_me{ try{1/0}catch{say "Caught [$@]"; return "AAA"}; return "BBB" } $v=try_me; say $v'


#############################################################
## Perl Modules - Unicode::Normalize
#############################################################

# Compose or decompose unicode strings.
perl -Mcharnames=:full -CO -MUnicode::Normalize -E 'say charnames::viacode ord for split //, NFD "\N{LATIN CAPITAL LETTER A WITH ACUTE}"'
# LATIN CAPITAL LETTER A
# COMBINING ACUTE ACCENT

# Get grapheme clusters.
perl -MEncode -MUnicode::Normalize -E 'use open qw(:std :utf8); say for map{ /(\X)/g } NFD "\x{61}\x{301}"'
á
perl -MEncode -MUnicode::Normalize -E 'use open qw(:std :utf8); say for map{ /(.)/g } NFD "\x{61}\x{301}"'
a

# Get individual decomposed characters.
perl -MEncode -MUnicode::Normalize -E 'use open qw(:std :utf8); say ord for map{ /(.)/g } NFD "\x{61}\x{301}"x2'
97
769
97
769
# LATIN SMALL LETTER A   U+61  0x61   97
# COMBINING ACUTE ACCENT U+301 0x301 769

# Use unpack to get unicode codepoints.
perl -MEncode -MUnicode::Normalize -E 'use open qw(:std :utf8); say for unpack "W*",NFD "\x{61}\x{301}"x2'
97
769
97
769
perl -MEncode -MUnicode::Normalize -E 'use open qw(:std :utf8); say for unpack "W*",NFC "\x{61}\x{301}"x2'
225
225


#############################################################
## Perl Modules - utf8
#############################################################

# decode then encode.
perl -MDevel::Peek -E 'my $v = "äöë"; sub c { say "#################"; say "is_utf8: " . utf8::is_utf8($v); say "valid:   " . utf8::valid($v); Dump $v } c; utf8::decode($v); c; utf8::encode($v); c'
#################
is_utf8:
valid:   1
SV = PV(0xb400007634f7a0b0) at 0xb400007634f89f98
  REFCNT = 2
  FLAGS = (POK,IsCOW,pPOK)
  PV = 0xb4000074f4f80650 "\xC3\xA4\xC3\xB6\xC3\xAB"\0
  CUR = 6
  LEN = 10
  COW_REFCNT = 1
#################
is_utf8: 1
valid:   1
SV = PV(0xb400007634f7a0b0) at 0xb400007634f89f98
  REFCNT = 2
  FLAGS = (POK,pPOK,UTF8)
  PV = 0xb4000074f4f7fd30 "\xC3\xA4\xC3\xB6\xC3\xAB"\0 [UTF8 "\x{e4}\x{f6}\x{eb}"]
  CUR = 6
  LEN = 10
#################
is_utf8:
valid:   1
SV = PV(0xb400007634f7a0b0) at 0xb400007634f89f98
  REFCNT = 2
  FLAGS = (POK,pPOK)
  PV = 0xb4000074f4f7fd30 "\xC3\xA4\xC3\xB6\xC3\xAB"\0
  CUR = 6
  LEN = 10

# encode then decode.
perl -MDevel::Peek -E 'my $v = "äöë"; sub c { say "#################"; say "is_utf8: " . utf8::is_utf8($v); say "valid:   " . utf8::valid($v); Dump $v } c; utf8::encode($v); c; utf8::decode($v); c'
#################
is_utf8:
valid:   1
SV = PV(0xb400007c1f6780e0) at 0xb400007c1f684f98
  REFCNT = 2
  FLAGS = (POK,IsCOW,pPOK)
  PV = 0xb400007adf667750 "\xC3\xA4\xC3\xB6\xC3\xAB"\0
  CUR = 6
  LEN = 10
  COW_REFCNT = 1
#################
is_utf8:
valid:   1



( run in 0.952 second using v1.01-cache-2.11-cpan-cdf2f3d4e48 )