Showing posts with label perl. Show all posts
Showing posts with label perl. Show all posts

This Week I Learned 2019 - Week 06

Last week post or you can going through some earlier stuff.

Happy new year again or rather, happy Chinese New Year. The weather was blazing hot compare to all the previous year even though there is no fire haze from our neighbouring country.

What else I've learned this week not within this post? Going through the sixth week of ornamental fish culture on fish breeding techniques such as selective breeding and biotechnology. Since this is a short lecture notes, I've decided to continue with week 7 study notes which discuss on seed production on factors affecting larvae rearing and feeding (species and water medium). The review paper of this week is the masculinization of the ornamental Siamese fighting fish with oral hormonal administration. SMS::ClickSend is the Perl module of the week to be reviewed.

Is Nokia 6303c still available these days? The most memorable and funny post I've read so far this year. I'm not sure under what context the poster needs to use a durable normal dump phone, but moving from Nokia 6303c, Nokia 216, Nokia 150, and lastly CAT B30 His perseverance is commendable and definitely should be the coolest post (not coolest use) of Perl usage writeup. I miss the old monochrome dumb or feature phone which is durable, have long lasting battery, and purposeful usages (call, text, and defend). Does affordable dumb phones still exists (as in 2019) these days? Yes, there are quite a lot and the one that caught my attention are from Alcaltel model 10.54, 20.08, 20.51, 10.50. Why dump phone still have a market these days? Four words. Africa and senior citizen.

为何程序员找工作要有个黑名单?这是Github每星期的邮件里推荐的一个流行的Repo。看见这个Repo竟然有十多千个Star,没想到还蛮多大陆的同胞在使用Github。

What are the differences among the subroutines in Carp module? Carp is a Perl module that provides alternative subtitutions to to `warn` and `die` in Perl? The screenshot below summarizes it the best. If you want the similar backtrace feature but don't or can't change your Perl code, there is always a Carp::Always module that will patch the `warn` and `die` subroutine.


What does a long time developer want? "Build more long lasting artifacts." How? Contribute more to FOSS then, is as simple as that.

Is Makefile redundant? In some context, yes. Because if you've a shell available, any shell scripts should be sufficient enough to emulate a Makefile as shown below.
#!/bin/sh
    set -e

    case "$1" in
        up)
            docker-compose up -d
            ;;

        build)
            docker-compose rm -vsf
            docker-compose down -v --remove-orphans
            docker-compose build
            docker-compose up -d
            ;;
        *)
            echo "unknown verb: $1"
            ;;
    esac

Write and publish a book in ten minutes per day? (via HN) Is this doable? Yes, you can just sit there and stare at it for ten minutes. However, the ten minutes is just the appetizer, to get your started. Maybe you can be in the zone or maybe not but you did something, even through you're just sitting there. The thing is you must do it every day, and every day it get easier. Remember the Jogging Baboon?

However, your brain still works on the task subconsciously even after the time frame. If you're not writing a book, what else can you do in ten minutes per day then? Doubt so as you brain still process the task the whole day even after the timed duration. Hence, the ten minutes is just to bootstrap the task and you've spend a few hours later doing it subconsciously.

There is another important lesson here. When to stop. If you don't have any juice left, stop. Or if you doing very well like in the zone, stop so you can look forward to continue tomorrow.

What else can you do during the ten minutes duration? There are plenty of things such as writing a dairy journals (via Lobsters), pick up any new habits, 5BX exercise plan, core wars kata.

Perl Module(s) Of The Week - 2019 Week 02 - Module::CoreList

One of the issue when using Perl is the abundant list of Perl's modules. Finding the right modules can be overwhelming and sometimes frustrating. Duplicating, deprecating, or abandon modules is typical situation for a programming language which is 31 years old. Hence, which recommended Perl's module should you uses then? Start with the modules that came default with the Perl installation, the core list. How? By using the Module::CoreList module.

Installation and quick check of the module.
$ cpanm Module::CoreList
$ perl -e 'use Module::CoreList'

Now, let's write some code (`ex1.pl`) to list out all the core modules that came with Perl 5.29.6.
use strict;
use warnings;
use feature qw|say|;

use Module::CoreList;

say $_ foreach sort @{[Module::CoreList->find_modules(qr/.*/i, 5.029006)]};

Running the code and show the first ten results.
$ perl ex1.pl | head
Amiga::ARexx
Amiga::Exec
AnyDBM_File
App::Cpan
App::Prove
App::Prove::State
App::Prove::State::Result
App::Prove::State::Result::Test
Archive::Tar
Archive::Tar::Constant

So far so good. But do we need to write some code in order to make any query? No, there is a console utility, corelist that will do that. For corresponding command almost similar to our Perl's code before this.
$ corelist -v 5.29.6 | head

The following modules were in perl 5.29.6 CORE
Amiga::ARexx                                 0.04
Amiga::Exec                                  0.02
AnyDBM_File                                  1.01
App::Cpan                                    1.671
App::Prove                                   3.42
App::Prove::State                            3.42
App::Prove::State::Result                    3.42
App::Prove::State::Result::Test              3.42

Now some code reading. What interesting stuff can we learn from reading the source code of Module::CoreList?

(1) All the data, for example, Perl's version, starting from Perl 5 was hard-coded as large hash (see the `%released` hash).

(2) To prevent duplication, the changes (see `delta_from`, `changed`, and `removed` hash) of modules for each Perl version were stored as delta hash (see `%delta` hash).

(3) These use of `@_` pass through from one subroutine to another subroutine as shown below. See the `first_release_raw` subroutine.
sub a { say @_; }
sub b { &a; }
sub c { &a(); }
sub d { a(@_); }
sub e { &a(@_); }

b 1, 2, 3; # 123
c 1, 2, 3; # nothing is printed
d 1, 2, 3; # 123
e 1, 2, 3; # 123

(4) The END block is not a subroutine but a block of code that executed after all codes have been ran and before the Perl interpreter exited.

How about source code from corelist?

(1) *nix piping in Perl. See the example below.
    my @bundles =  map { $_->[0] }
                  sort { $b->[1] <=> $a->[1] }
                   map { [$_, numify_version($_)] }
                  grep { not /[^0-9.]/ }
                  keys %feature::feature_bundle;

Perl Module(s) Of The Week - 2019 Week 01 - Data::Money

Since this item was on my to-do list for quite some time and this is the first week of the new year, might as well proceed ahead and do it. Inspired by Python Module of the Week (PyMOTW), I will start a series of weekly blog posts to review and discuss any interesting Perl module(s) that caught my attention. Write up mostly will be on some code example, issue encounter, and what can we learn from the code, as in code reading.

Our Perl module of this week is Data::Money, which allows us to perform math operations on different currency in an object manner and let us understand how operator overloading works in Perl. Furthermore, this is a good example to showcase the actual implementation of PoEAA's Money class design (there are actual four Money class designs exists), which is a rather simple approach which does not allows multiple currencies operation. Nevertheless, an actual production ready implementation.

Installation and quick check of the module.
$ cpanm Data::Money

It seemed in latest Perl version (v5.28.0), the dependant modules, Locale::Currency and Locale::Codes will be removed from Perl core distribution.
$ perl -e "use Data::Money"
Locale::Currency will be removed from the Perl core distribution in the next major release. 
Please install it from CPAN. It is being used at /usr/local/lib/perl5/site_perl/5.28.0/Data/Money.pm, line 27.
Locale::Codes will be removed from the Perl core distribution in the next major release. 
Please install it from CPAN. It is being used at /usr/local/lib/perl5/5.28.0/Locale/Currency.pm, line 22.

To remove the warnings, we have to install Locale::Currency manually.
$ cpanm Locale::Currency
$ perl -e "use Data::Money"

Let write some code (save as file `ex1.pl`) that create the new Money object or data type. `MYR` is the currency code where `MY` is two digits country code for `MalaYsia` and `R` is the name of the currency, in this case, `Ringgit`.
use strict;
use warnings;
use feature 'say';

use Data::Money;

my $price = Data::Money->new(value => 1.2, code => 'MYR');
say $price->as_string;
say $price->stringify;

Running the code will give us the same result twice. `RM` is the currency symbol that replaced our previous used `$` symbol.
$ perl ex1.pl
RM1.20
RM1.20

Let's look at these two subroutines, `as_string` and `stringify`. First, `as_string` is an alias to `stringify` subroutine. To create an subroutine alias in Perl, we will need to use typeglob (hence, the asterisk notation) to manipulate the Symbol Table, which stores all the variables in a package.
*as_string = \&stringify;

Second, as the name implied, `stringify` is typical subroutine naming convention for stringification in Perl, to convert an object into string or context of string. This is done through `overload` package as shown below, where it's implemented through anonymous subroutine. The subroutine will be invoked whenever the blessed package was called in a string context. You can read this tutorial for a sample working stringification using classical OOP way.
use overload
    '""' => sub { shift->stringify };

This Week I Learned 2018 - Week 52

Last week post or every damn thing from the past. As this is the last week of year 2018, this will be the last second post of this year before the reflection post at the eve of the new year.

What is the plural of fry (a group of little fish)? Is fries, as in like french fries. Every time when I jotted down my observation note on Betta fish breeding, I always confuse about the grammar.

The use of carcinogenic pesticides in our local rice, will this ever get regulated and monitored? Doubt so but our neighbour country, SG will surely let us know. While pesticide residues found in our food sources (especially beloved chili) and diet is still worrisome, there is still lack of conclusive evident linking pesticides to cancer.

Who is Larry Wall and how he is like? The creator of Perl programming language, the author of "The Three Virtues of a programmer", whose favourite colour is Chartreuse, an INFP, and unassuming. Also, some said he is Weird Al in disguise..

How to Get Things Done When You Don't Feel Like It? Use and apply these five strategies: (1) Gamify your process. Start with the smallest possible step that you don't have any excuses not to start. (2) Reserve calendar time for every project. Mark it in the calendar as any other important items in your life. Allocated a short period to do your next smallest item. (3) Get other people involved. Accountability is the key here. We will likely follow through what we promise others. Example is the daily scrum. (4) Talk about it. Externalizing problems by venting it out. (5) Practice the art of "precrastination". Do something else satisfying that release "dopamine" like checking off a to-do list or a short break.

The Everloving Perl's Constant - Part 2

In the previous post, we've look into declaring and using constant within the same module. How about using a constant from other package?

Let's create a sample `FooBar` module (FooBar.pm) which exports a constant, `COLUMNS` as shown below.
package FooBar;

use strict;
use warnings;
use Exporter qw(import);

use constant COLUMNS => qw(TEST1 TEST2 TEST3);
our @EXPORT_OK = qw(COLUMNS);

1;

To use this in another Perl script (test.pl). Notice there are several ways to use and access the `COLUMNS` constant.
use FindBin; # current script path
use lib "$FindBin::Bin"; # append current script path to the Perl's library path
use FooBar 'COLUMNS';

use strict;
use warnings;
use feature 'say';

say FooBar::COLUMNS();
say FooBar->COLUMNS();
say FooBar::COLUMNS;
say (COLUMNS);
say (COLUMNS());

1;

Should we use constant pragma in Perl? No, according to Damian Conway in this book, Perl Best Practices. Instead he advocates that we should "use named constants, but don't use constant."  What he meant if you want to use constant in Perl, use the Readonly module instead of the constant pragma. However, Perl Best Practices was written in 2005, 13 years ago. Hence, which begs the question, does the recommend practices still relevant for these days? Nope, even Modern Perl 4th Edition, published in 2016 also discourages the use of bareword constant.

So, if we still want to use constant in Perl, what is the modern take (as in 2018) on Perl's constant? Discussion at Reddit leads to two Perl modules, Const::Fast or ReadonlyX. I like the former for its speed (even though benchmark results doesn't differ much) and simplicity as shown below (example taken from the module doc).
use Const::Fast;
 
const my $foo => 'a scalar value';
const my @bar => qw/a list value/;
const my %buz => (a => 'hash', of => 'something');

I've read and seen developers who work around this problem by using  scalar through `our`and uppercase to declare variables.
our $COLUMNS = qw(TEST1 TEST2 TEST3);

Some even encapsulate these constants within a subroutine (which is true anyway as constant in Perl is an anonymous subroutine) with predefined values.
sub COLUMNS {
    return qw(TEST1 TEST2 TEST3);
}

Nothing wrong with that as there are developers who don't even want to bother with Perl's caveat. Furthermore, benchmark shows that these two methods, using variable or subroutine, is faster than using constant pragma. Maybe they are right. Perl, a weakly-typed and TMTOWTDI programming language, should be "abused" and treated like one.

In the end, should we even bother? Yes. After the comparison of 21 Perl modules that implement constant (yes, 21 bloody ways and that was written in 2012), it's good to stick to a standard way of using constant in your code base. Be it a constant pragma or Const::Fast module, just stick to one.

The Everloving Perl's Constant - Part 1

Constant in Perl is a pain in the arse to use rather than not use. It took me quite a while to figure this out. And again, Perl's TMTOWTDI strikes again.

Following this question asked in SO, let use this example as shown below.
package FooBar;

use strict;
use warnings;
use feature 'say';

use constant HTTP_OK => '200';
use constant COLUMNS => [qw/ TEST1 TEST2 TEST3 /];

say @{+COLUMNS};

1;

Since `COLUMNS` is a constant reference to an array of three elements, to fetch values from the constant, we must dereference it first through the `@{}` sigil.

However, there is a caveat here. In Perl, compare to other programming languages, a constant is not really a constant in normal convention. Rather, it's a prototype functions or a special kind of subroutine. If you use constant in the context that automatically quote barewords, in this case, dereferencing an array, `COLUMNS` may be interpreted as string and causing compilation errors as shown below.

say @{COLUMNS};

Ambiguous use of @{COLUMNS} resolved to @COLUMNS at test.pl line 11.
Variable "@COLUMNS" is not imported at test.pl line 11.
        (Did you mean &COLUMNS instead?)
Global symbol "@COLUMNS" requires explicit package name (did you forget to declare "my @COLUMNS"?) at test.pl line 11.
Execution of test.pl aborted due to compilation errors.


Thus, to prevent this, we need to tell Perl to ignore automatic quoting. How, there are two ways. First, use a special unaray symbol, like plus or ampersand sign as shown. Second, call the constant as a Perl subroutine.
say @{+COLUMNS};  # first way, plus sign
say @{&COLUMNS};  # first way, ampersand sign
say @{COLUMNS()}; # second way

Similarly, if we want to use a constant in hash key, we have to prevent the automatic bareword quoting. There are many ways.
%response = (HTTP_OK() => 1);
%response = (+HTTP_OK => 1);
%response = (&HTTP_OK => 1);
$response{HTTP_OK()} = 1;
$response{+HTTP_OK} = 1;
$response{&HTTP_OK} = 1;

Not using fat arrow (=>) but plain comma.
%response = (HTTP_OK, 1);

Alternatively, instead of using array reference, we can declare the constant as list instead.
use constant COLUMNS => qw/ TEST1 TEST2 TEST3 /;

Since the `COLUMNS` constant is a list context, assessing it should be placed in the parenthesis. And calling it as Perl sub works as well.
say (COLUMNS); # first way
say COLUMNS(); # second way

Comparing between two ways, initialization using list is more readable as we do not need to dereference the constant. For example, when looping through the constant.
foreach (COLUMNS) {
    say $_;
}

Instead of dereferencing.
foreach (@{+COLUMNS}) {
    say $_; 
}

Interesting right? That's the way of Perl's TMTOWTDI.

This Week I Learned 2018 - Week 43

Last week post or something else from the archive instead.

What should you do when you're taking vacant possession of the new property in MY? Download (PDF) the document CIS 7:2014 QLASSIC (Quality Assessment System in Construction) from CIDB (Construction Industry Development Board Malaysia). Read it, print our the checklist, and go through your property to check for any defects. A homeowner have the legal rights to request property developer to rectify any issues within the Defect Liability Period (DLP). Is there any property developer who dares to include this checklist and document during the handover of a new property? Doubt so.

What is like to be a engineering manager? You have no power, take the heat for your team, and mostly focus on management (office politics).

Can you explain JavaScript's closure like I'm five? So many explanations but this example is simple enough to understand. The next step is to understand how closure was used in JS world. Current stage is like you know how to hit a pool ball but don't know why you need to hit it in a certain way.

What the heck is Perl11? (via HN) Well, is Perl 5 + Perl 6. Again, endless drama on the direction of the language itself. Perl have the opportunity to shine and lead the way but lost it. Perl 6, on the other hand, is too little too late.

What are $_, @_, %_ used for? I was quite surprised by the reply, but this answer was outstanding. The `$_` known as default topic variable can be referred as "fill in the blank". How come I never think of that analogy?

What are the non-free installed in your GNU/Linux distribution? Well, you can ask virtual RMS. Running this in my lappy shows the usual suspect packages. Yes, the proprietary drivers or firmwares still remains an unsolved problem for FOSS ecosystem that does not follow the Free System Distribution Guidelines (GNU FSDG).
$ vrms
                Non-free packages installed on x230

amd64-microcode                     Processor microcode firmware for AMD CPUs
fonts-ubuntu                        sans-serif font set from Ubuntu
i965-va-driver                      VAAPI driver for Intel G45 & HD Graphics family
intel-microcode                     Processor microcode firmware for Intel CPUs

                Contrib packages installed on x230

iucode-tool                         Intel processor microcode tool
ttf-mscorefonts-installer           Installer for Microsoft TrueType core fonts
virtualbox-5.2                      Oracle VM VirtualBox

  4 non-free packages, 0.2% of 2788 installed packages.
  3 contrib packages, 0.1% of 2788 installed packages.



This Week I Learned 2018 - Week 41

Last week post or rather, old stuff from the archive.

Do we have an obsession with home ownership? (via /r/malaysia) While the discussion was referring to fresh graduates who are started out, the general rule of thumb still applies for everyone. Don't buy a house if you don't intend to stay more than ten years. Or don't buy houses 3 times more than your annual salary. Never equal home ownership like status symbol (just like car), you're taking a huge financial risk and long term repayment period. Another approach is to start small buy buying a low cost flat, stay in it, rent it, and sell it to buy a better house.

Judging by the current trend through NAPIC (National Property Information Centre), it's best to rent and wait before buying. Furthermore, the saving from your monthly mortgage installment into other investments will out weight the interest paid and potential capital appreciation of your property. By the time you're ready for retirement, might as well move to some where outskirts and rent again and live off the dividends of your investment in your golden years. Off course, if you're planning to get marry and owning a home is crucial to satisfy your SO and in-laws (another status symbol issue), first time homeowner can apply through PR1MA, which was created to prevent wealthier people from inflating the housing prices.

Now, instead of taking advice from armchair experts in the forum, why not do your own calculation using the The New York Times' rent or buy calculator.

Ignore this discussion if you're one of those crazy rich Asians.

And by the way, there have been quite a discussion where the upcoming Budget 2019 will have an impact of the housing prices. We will wait and see then.

Do you need a bigger house? No. We spend majority of our times in the kitchen, living room, and bed room. Perhaps a SOHO (Small Office Home Office) suite is a preferable choice if you don't have kids or big family.

How many ways to refresh a page in Google Chrome? Three. Only if you've open the Chrome Dev Tools and right click the refresh button as shown in the screenshot below illustrates this. Now, what are the differences between these three refreshing methods?  Normal reload will use re-validate and use cache files when needed. Hard reload will skip the cache and re-download everything again. As the name implies, empty cache and hard reload will clear the cache file and re-download everything.


What the fsck with Perl's constant? Besides the default `use constant` pragma, we have 21 (yes, bloody 21 ways) Perl's modules to deal with constant or readonly values. Worse still, none of these modules satisfy the needs of proper constant usage, it's a case by case basis. The recommended one is Const::Fast. More on this in coming posts.

This Week I Learned 2018 - Week 40

Last week post or something from the past.

What is the most expensive Koi fish sold at this moment? USD 1.7 millions! Yes, that was bid for for a champion Koi fish from Sakai Fish Farm. From the video's comment, the lady bidder is Chung Ying Ying, the Koi queen from Taiwan. Not really a fan of Koi fish as I do enjoy viewing fishes from side view instead from the top.

How can you write longer articles without adding more words? Switch to Times Newer Roman font which extends each character by 5 to 10 percents wider.

Why I'm grateful to live in MY instead of ID. (via Reddit) It's quite crazy there were so many instances of earth quake or typhoons at our neighboring countries. In return, we got their haze and labours.

Why should I croak instead of die? Use croak for the caller mistake and use die for the code mistake. According to the Carp module documentation,
The Carp routines are useful in your own modules because they act like die() or warn(), but with a message which is more likely to be useful to a user of your module. 
What if the subroutine returns a list but you want to assign it as an array reference? Use anonymous array.

How to resolve "Cannot determine local time zone" in Ubuntu under WSL environment? You will need to reconfigure your timezone again as a workaround for WSL constraint.

This Week I Learned 2018 - Week 38

You may like to read archived posts or something from last week?

What happened if your Perl's structure exceeded maximum nested level? You will get this error message of "json text or perl structure exceeds maximum nesting level (max_depth set too low?." I was surprised that certain structure may reach over the default level of 512 (a sign for you to redesign your data structure). Changing the 'max_length' threshold to unlimited did not solve the problem. Likewise, switching to the faster JSON::XS. Looking through the data structure did not indicate any circular loops? Due to time constraints, in the end, I just switched from text to binary serialization through Sereal package (benchmark wise is better than others).

What happened when you exceed the maximum daily exposure to Bisphenol A (BPA)? (via Reddit) So many things that can mess up your immune and nervous system. You should avoid drinking from soda can, plastic bottle number 3, 6, or 7, plastic cups, and paper receipts (those using heat). One thing for sure, avoid drinking from any plastic bottles exposed to the sun (especially left in the car). Temperatures shift may leach this chemical into the drinking water. What worse is there is so little studies on the side effect of this chemical, we may only figure out the harm it causes in coming 30 till 50 years. For now, just use nothing but stainless steel (18-8 food grade) bottle (e.g. Klean Kanteen) or glass jar. Also, do no microwave food in plastic container or wash them in dish washer.

Worse still, there are more of these harmful chemicals. The American Academy of Pediatrics have written a policy on identifying and preventing these chemicals from entering our body. If the paper is too long, read the summarized version by Harvard Health.

How do you slow down a gif image? Use GIMP and GAP libraries and adjust the delay between frames.

Why Git was more popular than Mercurial? (via HN) The battle of DVCS have long won by Git (largely due to GitHub and GNU/Linux) even though Mercurial provides a better usage experiences and documentation, based on my biased preference opinion. I'm quite surprised that a bottleneck performance issue (as it was written in Python?) in large repository is still not resolved after all this while even though performance-wise, both are quite the same (old benchmark in 2011, things have surely changed). What's next for DVCS? Pijul, written a Rust and inspired by Darc. But I doubt it can dethrone the popularity of Git in coming future.


This Week I Learned 2018 - Week 33

Last post or some random posts from the archive.

Do you need standups? Maybe you don't. (via HN) Some comments in HN resonate with me based on the experience of the implementation. Maybe is just me, but it does feels like cargo cult software engineering. Team culture, business culture, or management issue? Execution of the practice is still al lot to be desired. Interesting development days ahead.

What are Thonet & Vander speakers like? The sad case in MY here is that there is no way for us to purchase any good budget speakers. The funny thing is that this particular brand Thonet & Vander is readily available. Some local distributor have brought this in (why that particular distributor did no brought HiVi Swan to MY?). Nevertheless, as the comment suggestion, this is one of those OEM manufacturer which use European brand names to implies good quality. Back to the question, is this brand of speaker good enough? My personal opinion, mostly are multimedia speakers (something you bought for your kids) and Amazon's reviews didn't justify anyone to fork money on it (there are other brands exists in similar market, Edifier). Unless we have good review from NO Audiophiliethis comment shares my sentiment.

Which "budget" stereo amplifier to get? It's between Onkyo A-9010 and Marantz PM5005. Price wise both are the same and it's just the sound signature. For A-9010, I'm not sure that I need to replace the Samwah capacitor to Nichicon gold tune capacitor. However, different country have different version. However, I'm not sure the model sold here is EU (digital inputs and normal capacitors) or UK (better capacitors, no digital input, and Wolfson WM8718 DAC) version. Having digital input is good if you want to hook up to Chomecase Audio via Toslink input. Also, the loudness button (which increases sounds at low volume, good for classical music like Boléro) piqued my interest with the device.

Why not stick to amplifier like SMSL SA50 which is cheaper? Those class D amplifier is truly budget amplifier which missing quite a lot of features compare to amplifier like A-9010, a class AB amplifier. Furthermore, the output rating have been inflated. Class D amplifier should be sufficient enough for a small room.

Speaker wise. Just pair it up with a floor standing speaker if you don't want to invest a sub-woofer. The speaker's bass should be sufficient enough.

Encountered this error "Odd number of elements in anonymous hash..." and took me a while to figure out what went wrong with the the code. It turned out that Perl's hash will accept single element Hash without a key-value pair. Hence, the warning. I was surprised that this is not a syntax error. The example code below. See if you can identify the issue. Hint, the `foobar`. There is a good explanation at Stack Overflow on this warning message. Turn on warnings people!
my $result = $api->GetSomething({name => {'foobar'}});

This Week I Learned 2018 - Week 25

Week 24 post and something from archive.

中国最后的剑圣, 于承惠。在中文影坛里,在也找不到另一个演员能诠释演出这个角色,从霸气的恶人角色到闭山修行的一代宗师。可惜,晚年在影坛没参与任何武侠片。

How to Survive Your 40s? (via KH). As someone who going to take a leap into this new decade, I can probably relates (the screenshot below tells quite a lot as well) to the author experience. Since few years back, younger people have started to call me "uncle" (my choice of clothing did contribute to that as well). It's a sudden but natural shift that comes with your age. The article reminded me of a Korean movie (can't remember the name) I've watched few weeks back. Basically the protagonist (someone in his 50s) said you need to see this milestone as the second 20s. The second time for you to reflect or follow up with what you've done (differently this time) in your 20s. The to-do list since so many years ago is still so long and it will keep me occupied for so some times.



What the difference between Perl and Python? If you need a comparison between both programming languages, this book, "Scripting with Objects: A Comparative Presentation of Object-Oriented Scripting with Perl and Python", while quite dated (it was written in 2008), provides some insights on differences between these both programming languages. In the end, the rising popularity of Python and emergence of Perl 6 shown that, opinionated or there should be a standard way of doing things won.

Why you need to set default value in `sub` in Moo or Moose? Because having a subroutine wrapper returns a unique reference every time you create a new object.

How do you boot from USB thumb drive from Grub itself? Yes, this is possible (do read the whole discussion). You must go to the Grub console by pressing 'c'. Remember that you can tab to find out which removable media and partition to use. It's quite annoying that sometimes the BIOS cannot detect the removable media (thumb drive) and can't boot from the device itself.
grub> ls
grub> set root=(hd1, msdos2)
grub> chainloader +1
grub> boot

On a related note, migration from Fedora 27 to Fedora 28 was such a painful experience. The keyboard and mouse did not work and were very lagging. I'm not sure, but Fedora 28 was such a let down. In the end, have to wipe out the whole installation and replaced it with Ubuntu 18.04 and everything works as intended. Seriously, Fedora, what is going there with 28 release?

Why they said Perl is a more advanced scripting language for system administrator? See App::GitHubPullRequest, a Perl console tool that glues together three different console tools of git, stty, and curl.

How to train your kids to do house chores voluntarily? (via HNEmpowerment since toddler.

Dreadful tasks? Just try, give it a while.

Which Perl modules to use when making HTTP requests? There are so many.

How does you do dispatch table in Perl? Found an old discussion (2010) in HN. The book High-Order Perl have a whole chapter (PDF) on this topic.

This Week I Learned 2018 - Week 24

Previous week post and from the archive.

When you have so many fishes died and so many was born in the same week, it did bring a whole new meaning regarding the circle of life. However, looking closely, it's simply just the incorrect water parameters issue in multiple aquarium tanks.

How the heck we return an array reference when using Perl's map to manipulate each element in the array list? The answer is quite straightforward, using bracket `[]` to wrap the list in array context.
use Data::Dumper;

my $items_in_lowercase = [ map { lc($_) } ('Foo', 'Bar', 'Baz') ];
print Dumper($items_in_lowercase);

What are the available core modules in your Perl installation? Use `corelist`, a command line front end to Module::CoreList to find out.

How does a Perl's coding standard documentation looks like? The SEI (Software Engineering Institute) Cert Perl coding standard not only well organized, it's also well written. Really put some software companies own documentation to shame. To be fair, this is from SEI, yes, the one that introduced CMMI (Capability Maturity Model Integration).

Writing and releasing free and open source software? Which license to choose? Pick one that suite you then.

Are you working on interesting technical problems? "You might as well have asked who among us won the lottery." The top post has the best answer I've read since so long. The whole discussion not really about the technical problems but more towards your attitude towards it.

How do you handle undefined methods in Perl? AUTOLOAD or Autoload::Can, or Mojolicious' AutoLoader? Either ways is still a hack somehow or another when compare to other programming languages implementation.


This Week I Learned 2018 - Week 23

Last week stuff or something from the archive.

We're half way through the year of 2018. Some new adjustment to my weekly blogging. Starting from this week, more question and answer style of writing.

Old school or just plain hipster? It seemed that the newly appointed important person does not or will not use a mobile phone. Interesting indeed.

What happened when the town beats the land in a sweep? It will get boring and expected, the usual classic rags to riches story line. We need more competition, super teams, and nemesis within the NBA league for the next coming seasons.

What happened when your stakeholders want to start a project that requires "seven red lines" ? Brutally honest or diplomatically tactful?

Does open office have a big impact towards deep work? And does it matters? The discussion in HN yields a few interesting points but the main question remains, why organization still insists on open office and expects deep work?

Is QBASIC a good beginner programming language? The sentiments in the HN members believed so, so do I. Simple (yes, even simpler than Python) and easy to get it up with a good TUI. For a modern equivalent, load81 is probably the closest thing.

Should you use your ISP's DNS server? Hell no. Switch to either Cloudflare's 1.1.1.1 or Google's 8.8.8.8. Not only you gain faster domain resolving speed, you also have privacy (debatable). When comes to implementing privacy in DNS, it seemed we have three protocols of DNSCrypt, DNS over TLS, and DNS over HTTPS.

Should you learn multiple programming languages or master one? Depends. Different people have different motivation, learning strategies, and priorities in life. Either one should works. Do what you love and love what you do.

How do you improve your writing skills? Measurement and volume. First, "you improve what you measure", a very metric-driven way of doing it. However, this may backfired as according to Goodhart's law, "When a measure becomes a target, it ceases to be a good measure.". Second, just write, deliberately, in fixed amounts of words. How? First, don't judge your works, forget grammar and spelling, just churn out words. The Emacs's typewriter mode is a good strategy.

When come to superheroes, how do you justify the existence a character without any special super powers? They have better soft skills and less ego than more powerful super heroes. Watch A critical component for a better visual answer. I almost chocked myself laughing non-stop while watching this, repeatedly.

How do we implement operator overloading in Perl? Use `overload` package. Example of good implementation is the `Data::Money` package.

This Week I Learned 2018 - Week 22

Last week post or something else instead.

为什么同级相斥,异级相吸呢?这不是指磁铁的原理,而是可以用来形容两个同样作风的领袖都会同样排斥。客观的见解来看待各国领袖的作风。

It actually dawned to me that `eval` is quite similar to try-catch block. If your language did not have the support of try-catch exception handling, `eval` (yes it's evil) is your friend. Even Try::Tiny have its own issues. Perl is really a f-up programming language.

VS Code can do that? (via HN) I still haven't have time to install VS Code in my lappy and set up all the necessary configuration and settings.

What's the point of Perl's map? To transform list without using for (each) loop. Is as simple as that and yet we still having hard time understand that? Another good discussion on different between `map` and `grep`, the former is to process a list, the later is to filtering a list.

Containers according to xkcd. Sometimes the simplest solution is the best solution.

30 is too old for tech job in China. (via HN)

REST API tutorial. Yes, I've done a few wrapper for third parties API and two common issues are not up-to-date documentation and inconsistency, especially when handling different HTTP responses.

Block EU users from accessing your site due to complication of implementing GDPR. Brilliant or just simply crazy. And then you have the GDPR compliance checklist or search through the whole GDPR legislation document instead from the original source or community curated info. GDPR is probably the best things that happened to protect user privacy and reduce the abuse of any organizations on handling our personal data.

"Just write. You'll find your own voice". Probably the best common advice given to anyone who wish to become better at writing. For something related to writing, Janki Method, an approach to learning. When you learn something new, write it down but in an approach of question and answer. Maybe you can use a flash card or something.

Stack Overflow for Team. Interesting, very interesting indeed. I chuckled when I saw this feature was released. Wonder how it likes to re-implemented someone else features. Yeah, we should see things from both ends. DRY can be violated if necessary, only if necessary.

Yeah, making money is nothing but how much you care about making money (emphasis added).
Caring a lot about specifically making money is, in my opinion, absolutely key to making money, because otherwise you just end up focusing on other things (family, pleasures, ideals, etc.). If I wanted to make money, I'd design a very different thing in a very different way compared to if I wanted to make something me and my circle of friends would find useful. These things are practically disjoint.

This Week I Learned 2018 - Week 21

Previous week post or something from the past.

Malaysian honorific title, an analysis. How many Datuk, Tan Sri, and others have been granted by each state. Yes, you can check whether a person have received any honorific title.

The more I coded with Perl, the more I've learned something so obvious that I didn't pay much attention. For example, to check if a method or subroutine exists in a class or package, use `can()`.

Check if method exists and invoke it.
sub make {
  my ($self, $item) = @_;
  my $method = "make_$item";
  if ($self->can($method)) {
    $self->$method(whatever);
  } else {
    die "No such method $method";
  }
}

Another approach, using reference. If the method or subroutine not found, `undef` returned.
if ( my $ref = __PACKAGE__->can("$method") ) {
    &$ref(...);
}

Check if a hash is empty? Perl's TMTOWTDI is just crazy.

if (%foo) {
    # %foo has at least one key
} else {
    # %foo has no keys
}

What is the closet HTTP method equivalent to ping? HTTP HEAD.

2018 Perl survey results. Surprised to look at the result of the age group. Two things that caught my attentions. First, there are developers who still code in their 70+ years old. Second, young new developers have been declining. You can see the trend there, Perl it's a dying programming language.


This Week I Learned 2018 - Week 20

Week 19 post or something from the past.

Interesting development on the local scene. Everyone is overwhelmed by the endless good news which some seemed too good to be true. Still too soon to tell but nobody think it will get worst than the current mess. On a side note, at least now we can read articles in Medium from our mobile devices.

The completion of BSL20180124. Our second successful spawn. As usual, write-up on the whole process and retrospection on our breeding process. Both of us are getting more experienced, selective, and bolder when breeding Bettas. So many things learned during these few months and what we learned can definitely can help us to improve our other spawning projects. We can now confidently buy better grade (ahem, more expensive) Betta fishes and breed them. But right now, the main focus is to change our breeding method from leaving fry with father to removing fry after free swimming. The former method produces limited number of fry and the later will yield large (till 500 fry) spawn. We shall see the result in coming months.

The difference between `application/xml` and `text/xml`. Encounter this when making RESTful request and the existing CPAN module does not recognizes `text/xml`.

Good sample Dockerfile to setup your Perl application in Docker instance.
FROM perl:5.26

RUN cpanm Carton && mkdir -p /usr/src/app
WORKDIR /usr/src/app

ONBUILD COPY cpanfile* /usr/src/myapp
ONBUILD RUN carton install

ONBUILD COPY . /usr/src/app

Detect whether an item exists in a Perl's array. Why such simple stuff needs to be so complicated in Perl?
# $value can be any regex. be safe
if ( grep( /^$value$/, @array ) ) {
    print "found it";
}

A Practical Guide to (Correctly) Troubleshooting with Traceroute (PDF). We have been using traceroute wrongly all this while.

This Week I Learned 2018 - Week 18

Last week post or something else from the archive.

最近无意看了汤浅政明《春宵苦短,少女前进吧!》,那个诡异及天马行空的画风及离奇爱情故事,非常值得一看及收藏的动画电影。导演另一个作品,《四疊半神話大系》,也值得一提。


FORMS. Interesting concept on how to manage your week. In other words, you have a daily theme or something you're going to focus on each day. For example,
  • Monday: Finances 
  • Tuesday: Operations 
  • Wednesday: Research & Development 
  • Thursday: Marketing 
  • Friday: Sales
Interesting learning experience with Perl and Travis CI. From how-should-i-start, to why-this-is-not-working, and finally-something-is-working, Axel Beckert's guide is a definitely must read material. Furthermore, the Travis-CI testing helper for Perl modules does help a lot. However, like most Perl modules out there, documentation and maintenance is still a major issue. No worry, there is a tool to bootstrap the `.travis.yml` file, just install App::CISetup and use `setup-travis-yml.pl`.

Having fun coding and can't seem to stop. Moderation is the key here.

kwalitee. Yes, kwalitee or Test::Kwalitee.

Facepalm. Totally speechless when using Dzil and Perl::Critic. You cannot put the package name in the first line of the code otherwise Perl::Critic will complain.
use strict;
use warnings;
package Foo;
# ABSTRACT: This is a Foo.
# KEYWORDS: foo bar baz

use frobnitz;
use OtherStuff;
...

This Week I Learned 2018 - Week 17

Last week post or something from the past instead.

Humour aside, I've known two persons (a tech guy and a lecturer) who don't even have a mobile phone, let alone social media accounts. Yes, they are on the rather extreme cases but that was due to their own personal stands and life philosophy. While there have been quite a lot of minimalist life style movement these days but little emphasis on digital world. As usual, moderation is the key here. Too much of everything will cause unwanted disturbance and distraction to your personal and working life.


The Playoff Rondo is part stats and part myth although the stats don't tell the full story. But it's quite entertaining to watch him play, especially the playoff and with big centers.

Plan B before you turn 40. (via HN) Relevantly, experiences on those over 50 who have been laid-off from the tech-force seemed quite positive, life still goes on although on different path. Well there are differences different between Western and Asia countries, this is just part of your work life, especially for those working in tech. Practice minimalist life style, live below your means, exercise and keep healthy, and do what you love. You have to agree with, web development is so accessible these days. Anyone good basic knowledge of English and keen persistence, they can build up the system fairly quite fast. Furthermore, as you aged, priority in life changed as well as your health. Moreover, older tech guy tends to question more and call out BS.

Where SCRUM is not the right choice. (via Reddit) The discussion in the Reddit tells a lot of the horror or abuse stories where SCRUM was implemented literally. It does not work for software team with different project and don't share the SAME backlog. If you have different products, you can't implement SCRUM within the same backlog! Period.

Friendship’s Dark Side: ‘We Need a Common Enemy’. It's a common knowledge but right now it have been proven that "Xenophobia and in-group bias go hand-in-hand". Average fall-outs withing the social group is around 7-plus months. Interesting read.

One item checked off the bucket list. More items to go.
$ cpanm Webservice::Swapi
--> Working on Webservice::Swapi
Fetching http://www.cpan.org/authors/id/K/KI/KIANMENG/Webservice-Swapi-0.1.1.tar.gz ... OK
Configuring Webservice-Swapi-0.1.1 ... OK
Building and testing Webservice-Swapi-0.1.1 ... OK
Successfully installed Webservice-Swapi-0.1.1 (upgraded from 0.1.0)
1 distribution installed

Select all parent and child records. This is when having a Venn diagram really help in visualizing the details.
SELECT ...
FROM comments AS parent
LEFT JOIN comments AS child 
ON child.parent_id = parent.id
WHERE parent.parent_id IS NULL
ORDER BY parent.id, child.id;

Cpanm with local library installation

One of the issue I kept facing when developing local Perl modules installation and dependency management.

$ cpanm -nq --installdeps --with-develop --with-recommends .
!
! Can't write to /usr/local/share/perl/5.26.0 and /usr/local/bin: Installing modules
! to /home/foobar/perl5
! To turn off this warning, you have to do one of the following:
!  - run me as a root or with --sudo option (to install to 
!    /usr/local/share/perl/5.26.0 and /usr/local/bin)
!  - Configure local::lib in your existing shell to set PERL_MM_OPT etc.
!  - Install local::lib by running the following commands
!
!    cpanm --local-lib=~/perl5 local::lib && eval $(perl -I ~/perl5/lib/perl5/ -Mlocal::lib)
!

Either we do this manually everytime.
$ cpanm --local-lib=~/perl5 local::lib 
$ eval $(perl -I ~/perl5/lib/perl5/ -Mlocal::lib)
local::lib is up to date. (2.000024)

Or setup your local environment for once through local::lib.
$ PATH="$PATH:~/perl5/bin"

Additional directories for Perl library.
$ export PERL5LIB=~/perl5/lib/perl5

Options for Module::Build.
$ export PERL_MB_OPT="--install_base '$HOME/perl5'"

Options for Module::MakeMaker.
$ export PERL_MM_OPT="INSTALL_BASE=$HOME/perl5"

$ curl -L http://cpanmin.us | perl - -l ~/perl5 App::cpanminus local::lib

Add this to your `.profile` as well.
$ eval $(perl -I$HOME/perl5/lib/perl5 -Mlocal::lib)
$ source ~/.profile # reload

Or just use Perl's Docker container image.

Or just use Carton and set everything to local folder.