Sharing

2013年5月30日 星期四

Abbreviation of software release life cycle


公司寄了一份 "Hand Book" 電子檔.. 結果打開來二百多頁 =.= , 這是那門子的 handbook
裡面有一堆的縮寫, 有些是業界還滿常見的用法, 記下來免的聽不懂別人說什麼

http://en.wikipedia.org/wiki/Software_release_life_cycle

  • Release Candidate (RC)
  • General availability (GA)
  • Release to manufacturing (RTM)
  • Golden Master (GM)
  • Product Integration Test (PIT)
  • Service Engineer Group (SEG)
  • Product Development Group (PDG)
  • Core Tech Certification Center (CTCC)
  • Collaboration Project Manager(CJM)
  • Data Center Service (DCS)
  • Service Operation Center (SoC)
  • Service Delivery Team (SDT)
  • Iterative Development Process (IDP)
  • Product and Service Development Lifecycle (PDLC & SDLC)
  • Definition of Done (DoD)
  • Earned Value Measurement (EVM)
  • Web Services Engineering (WSE)
  • Early Engagement Testing (EET)
  • Requirement Traceability Matrix (RTM)
  • Market Requirement Document (MRD)
  • Product Requirement Document (PRD)
  • Product Planning Committee (PPC)
  • Collaboration Project Manager (CJM)
  • Service Level Agreement (SLA)
  • Proof of Concept (PoC)
  • Service Level Objective (SLO)
  • Software Requirement Specification (SRS)
  • Product Build Environment (PBE)
  • Development Build Environment (DBE)
  • Test Case Management Server (SCTM)


     * 數字代表中間的英文字母數量







2013年5月29日 星期三

Background Color of Shell Terminal

原本用 Ubuntu 內建的 Terminal, 顏色很正常, 看起來也很舒服




但在用 Gnome Connection Manager 時, vi 的藍色突然變成高亮度, 眼睛一整個看不清楚, 不知道要怎麼解決這個狀況, 於是就想說來調一下背景色


找了一下網路文章
http://www.hanselman.com/blog/VisualStudioProgrammerThemesGallery.aspx
http://www.codinghorror.com/blog/2006/09/is-your-ide-hot-or-not.html

最後試了半天, 決定採用 RGB(64/64/64) 這個背景色, 雖不十分滿意, 但還算可以接授
畢竟只是短暫的工作環境




.vimrc


後來同事建議我修改 .vimrc 比較快 XD

syntax on
set bg=dark
set nocompatible
set number
set shiftwidth=4
set softtabstop=4
set linebreak
set nowrap


Bash Keyboard Shortcuts

Keyboard Shortcuts

比較完整的在這篇裡面
http://halotis.com/2010/07/06/bash-keyboard-shortcuts/

列一些比較常用的

Moving the cursor

Ctrl + a Go to the beginning of the line (Home)
Ctrl + e Go to the End of the line (End)
Ctrl + p Previous command (Up arrow)
Ctrl + n Next command (Down arrow)
Alt + b Back (left) one word
Alt + f Forward (right) one word

Editing

Ctrl + L Clear the Screen, similar to the clear command
Ctrl + u Cut/delete the line before the cursor position.
Ctrl + k Cut the Line after the cursor to the clipboard.
Alt + backspace Delete the Word before the cursor.
Alt + d   Delete the Word after the cursor.

Ctrl + w Cut the Word before the cursor to the clipboard.
Ctrl + y   Paste the last thing to be cut

Ctrl + t   Swap the last two characters before the cursor (typo).
Alt + t   Swap current word with previous

Alt + u   UPPER capitalize every character to the end of the current word.
Alt + l   Lower the case of every character to the end of the current word.
Alt + / Attempt to complete filename

History

Ctrl + r Search the history backwards.
Ctrl + g Escape from history searching mode
!! Execute last command in history
!abc Execute last command in history beginning with abc
!n Execute n-th command in history

Other

Ctrl + x @ Show possible hostname completions.

Terminal Alt Shortcut Key Problem

Alt activate the menu item

Gnome Terminal 預設按 alt 會切換到 menu item. 但這會造成 Alt+f/Alt+b 無法使用, 如果想要取消這個功能可以在選單 Edit->Keyboard Shortcut 內把
"Enable menu access keys"
"Enable the menu shortcut key"
都移除勾選


Alt+left / Alt+right key  no use


在 Window/Putty 時,沒有這個問題,但在 Gnome Terminal 就出現了這個問題
檢查了一下 Alt+left key 的值, 發現在兩個環境內收到的不一樣!?

在 putty 環境內
# press Alt+left key
$ read
^[^[[D

# press Alt + right key
$ read
^[^[[C

在 gnome terminal 內
# press Alt+left key
$ read                              
^[[1;3D

# press Alt + right key
$ read
^[[1;3C

http://blog.simplicitymedialtd.co.uk/457/making-alt-leftalt-right-work-in-gnome-terminal-like-putty


目前還是不清楚為什麼會有這樣的狀況,但快速解法是修改 /etc/inputrc or ~/.inputrc
以滿足兩個狀況下的 Alt+array key 都能發揮作用

cat .inputrc
# mapping for alt+left-arrow and alt+right-arrow for word moving
"\e[1;3D": backward-word
"\e[1;3C": forward-word
"\e\e[C": forward-word
"\e\e[D": backward-word


2013年5月27日 星期一

Multiple Connection Manager

在 Window 上

在 Linux 上, 我找到有兩個可以使用
          中文介紹
          http://www.openfoundry.org/tw/foss-programs/8188-pacmanager

我自己選擇使用 Gnome Connection Manager, PAC 的功能太多, 一時間覺得有點眼光瞭亂, 不如就先用陽春的 GCM, 另一個選擇他的理由是它是用 Python 寫的, PAC 是用Perl 寫的, 對 Perl 實在沒什麼好感。

2013/05/31 Update:
寫信給 kuthulu.com , 想不到很快的就得到回答

editing the file /usr/share/gnome-connection-manager/gnome-connection-manager.glade

look for the following items:
menuitem1, menuitem7, menuitem5, menuitem6, menuitem4

and change
<property name="use_underline">True</property>
to
<property name="use_underline">False</property>

下方是我改過的檔案內容,改過之後 alt+f, alt+b 就可以使用了!
$ grep -P 'id=\"menuitem\d\"' /usr/share/gnome-connection-manager/gnome-connection-manager.glade -A 3
            <widget class="GtkMenuItem" id="menuitem1">
              <property name="visible">True</property>
              <property name="label" translatable="yes">_Archivo</property>
              <property name="use_underline">False</property>
--
            <widget class="GtkMenuItem" id="menuitem7">
              <property name="visible">True</property>
              <property name="label" translatable="yes">_Editar</property>
              <property name="use_underline">False</property>
--
                <widget class="GtkMenuItem" id="menuitem9">
                  <property name="visible">True
                  <property name="label" translatable="yes">Comandos personalizados</property>
                  
--
            <widget class="GtkMenuItem" id="menuitem5">
              <property name="visible">True</property>
              <property name="label" translatable="yes">_Ver</property>
              <property name="use_underline">False</property>
--
            <widget class="GtkMenuItem" id="menuitem6">
              <property name="visible">True</property>
              <property name="label" translatable="yes">_Servidores</property>
              <property name="use_underline">False
--
            <widget class="GtkMenuItem" id="menuitem4">
              <property name="visible">True</property>
              <property name="label" translatable="yes">Ay_uda</property>
              <property name="use_underline">False</property>


麥肯錫 12 technologies driving the future

Perl 語言編程第四版筆記(三)

Chapter 9 Data Structures


Arrays of Arrays


# Assign a list of array references to an array.
my @AoA = (
     ["fred", "barney" ],
     ["george", "jane", "elroy" ],
     ["homer", "marge", "bart" ],
);

print $AoA[2][1]; # prints "marge"
print $AoA[2]–>[1] # same command of previous one

# Create a reference to an array of array references.
my $ref_to_AoA = [
    [ "fred", "barney", "pebbles", "bamm bamm", "dino", ],
    [ "homer", "bart", "marge", "maggie", ],
    [ "george", "jane", "elroy", "judy", ],
];

print $ref_to_AoA–>[2][3];  # prints "judy"
print $ref_to_AoA->[2]->[3]; #same command of previous one

A CPAN module that we like to use for displaying our data dumps is Data::Dump.

use v5.14;
use Data::Dump qw(dump);
# for push on scalars
# CPAN module
my @AoA = (
    [ "fred", "barney" ],
    [ "george", "jane", "elroy" ],
    [ "homer", "marge", "bart" ],
);
push $AoA[0], "wilma", "betty";
dump \@AoA;

When constructing an array of arrays, remember to compose new references for
the subarrays. Otherwise, you will just create an array containing the element
counts of the subarrays.

$AoA[$i] = @array;          # Wrong!!
$AoA[$i] = [ @array ];      # Safest, sometimes fastest
$AoA[$i] = \@array;         # Fast but risky, depends on my–ness of array
@{ $AoA[$i] } = @array;     # A bit tricky


Chapter 10 Packages

The contents of a package are collectively called a symbol table. Symbol tables are stored in a hash whose name is the same as the package, but with two colons appended. The symbol table for the Red::Blue package is named %Red::Blue::.

Inside a symbol table’s hash, each key/value pair matches a variable name to its value. The keys are the symbol identifiers, and the values are the corresponding typeglobs. The following have (nearly) the same effect

*sym = *main::variable;
*sym = $main::{"variable"};

Print out the package hash table.

foreach $symname (sort keys %main::) {
    local *sym = $main::{$symname};
    print "\$$symname is defined\n" if defined $sym;
    print "\@$symname is nonnull\n" if         @sym;
    print "\%$symname is nonnull\n" if         %sym;
}



*PI = \3.14159265358979;
use constant PI => 3.14159;
*PI = sub () { 3.14159 };

The following are all equivalent to one another, though the first two compute the symbol table entry at compile time, while the last two do so at run time.
*sym = *oldvar;
*sym = \*oldvar;        # autodereference
*sym = *{"oldvar"};     # explicit symbol table lookup
*sym = "oldvar";        # implicit symbol table lookup

If you think about it sideways, the typeglob itself can be viewed as a kind of hash,
with entries for the different variable types in it. In this case, the keys are fixed,
since a typeglob can contain exactly one scalar, one array, one hash, and so on.

*pkg::sym{SCALAR}         # same as \$pkg::sym
*pkg::sym{ARRAY}          # same as \@pkg::sym
*pkg::sym{HASH}           # same as \%pkg::sym
*pkg::sym{CODE}           # same as \&pkg::sym
*pkg::sym{GLOB}           # same as \*pkg:;sym
*pkg::sym{IO}             # internal file/dir handle, no direct equivalent
*pkg::sym{NAME}           # "sym" (not a reference)
*pkg::sym{PACKAGE}        # "pkg" (not a reference)

sub identify_typeglob {
    my $glob = shift;
    print "You gave me ", *{$glob}{PACKAGE}, "::", *{$glob}{NAME}, "\n";
}

identify_typeglob(*identify_typeglob);  # print out "You gave me main::identify_typeglob"

The special symbol __PACKAGE__ contains the current package name

Autoloading


Skip First

Chapter 11 Modules

The opposite of use is no. The syntax :

no MODULE;
no MODULE LIST;
no MODULE VERSION;
no MODULE VERSION LIST;









Perl 語言編程第四版筆記(二)

Chapter 5 Pattern Matching


Skip first for time reason.

Chapter 6 Unicode


Skip first for time reason.

Chapter 7 Subroutines



sub NAME BLOCK
sub NAME PROTO ATTRS BLOCK
sub NAME BLOCK
sub NAME PROTO ATTRS BLOCK

To create an anonymous subroutine or closure, leave out the NAME.

To call subroutines directly,
NAME(LIST) # & is optional with parentheses.
NAME LIST # Parens optional if sub predeclared/imported.
&NAME # Exposes current @_ to that subroutine,

To call subroutines indirectly (by name or by reference)
&$subref(LIST) # The & is not optional on indirect call
$subref–>(LIST) # (unless using infix notation).
&$subref # Exposes current @_ to that subroutine.










Perl 語言編程第四版筆記(一)

Chapter 3 Unary and Binary Operators


Binary x is the repetition operator.
In scalar context, it returns a concatenated string consisting of the left operand repeated the number of times specified by the right operand.

print "–" x 80;        # print row of dashes

In list context, if the left operand is a list in parentheses or is a list formed by qw/STRING/, the x works as a list replicator rather than a string replicator.

my @ones = (1) x 80;      # a list of 80 1's
@ones = (5) x @ones;      # set all elements to 5

my %hash;
my @keys = qw(perls before swine);
@hash{@keys} = ("") x @keys;



Smart Match


So ~~ is often best read aloud as “matches” or “matches any of”, because the left operand submits itself to be accepted or rejected by the right operand.

Left Right Description Like
Any undef Check whether Any is undefined !defined Any
Any ARRAY Smartmatch each ARRAY element grep { Any ~~ $_ } ARRAY
Any HASH HASH key existence exists HASH–>{Any}
Any Object Invoke ~~ overloading on Object, or die

Any CODE Sub passed Any returns true CODE–>(Any)
Any Regexp Pattern match Any =~ /Regexp/
Any Num Numeric equality Any == Num
Any Any String equality Any eq Any








undef ARRAY undef in ARRAY grep { !defined } ARRAY
undef HASH Always false (undef can’t be a key) 0 == 1








ARRAY1 ARRAY2 Recurse on paired elements of
ARRAY1 and ARRAY2
(ARRAY1[0] ~~ ARRAY2[0]) && (ARRAY1[1] ~~ ARRAY2[1]) && ...
ARRAY HASH Any ARRAY elements exist as HASH keys grep { exists HASH–>{$_} } ARRAY
ARRAY CODE Sub returns true on all ARRAY elements !grep { !CODE–>($_) } ARRAY
ARRAY Regexp Any ARRAY elements pattern match Regexp grep { /Regexp/ } ARRAY








HASH1 HASH2 All same keys in both HASH keys HASH1 == grep { exists HASH2–>{$_} } keys HASH1
HASH CODE Sub returns true on all HASH keys !grep { !CODE–>($_) } keys
HASH
HASH Regexp Any HASH keys pattern match Regexp grep { /Regexp/ } keys HASH








Num numlike Numeric equality num == numlike


Range Operators


my @alphabet = ("A" .. "Z");
my $hexdigit = (0 .. 9, "a" .. "f")[$num & 15]
my @z2 = ("01" .. "31");
print $z2[$mday];
my @combos = ("aa" .. "zz");
use charnames "greek";
my @greek_small = ("\N{alpha}" .. "\N{omega}");

Logical and, or, not, and xor


my $x,$y,$z,$xyz;

$x = 0;
$y = 1;
$z = 5;

$xyz = $x || $y || $z;  # output 1

$xyz = $x or $y or $z;  # wrong, it will execute "="  before "or",  output 0

$xyz = ( $x or $y or $z );  # correct, output 1


Chapter 4 Statements and Declarations


Compound Statements


if (EXPR) BLOCK
if (EXPR) BLOCK else BLOCK
if (EXPR) BLOCK elsif (EXPR) BLOCK ...
if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK

unless (EXPR) BLOCK
unless (EXPR) BLOCK else BLOCK
unless (EXPR) BLOCK elsif (EXPR) BLOCK ...
unless (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK

given (EXPR) BLOCK

LABEL while (EXPR) BLOCK
LABEL while (EXPR) BLOCK continue BLOCK # for loop 的變形

LABEL until (EXPR) BLOCK
LABEL until (EXPR) BLOCK continue BLOCK

LABEL for (EXPR; EXPR; EXPR) BLOCK

LABEL foreach (LIST) BLOCK
LABEL foreach (LIST) BLOCK continue BLOCK
LABEL foreach VAR (LIST) BLOCK
LABEL foreach VAR (LIST) BLOCK continue BLOCK

LABEL BLOCK
LABEL BLOCK continue BLOCK

given statement


use feature ":5.10";
given ($n) {
    # match if !defined($n)
    when (undef) {
        say '$n is undefined';
    }

    # match if $n eq "foo"
    when ("foo") {
        say '$n is the string "foo"';
    }

    # match if $n ~~ [1,3,5,7,9]
    when ([1,3,5,7,9]) {
        say '$n is an odd digit';
        continue; # Fall through!!
    }

    # match if $n < 100
        when ($_ < 100) {
        say '$n is numerically less than 100';
    }

    # match if complicated_check($n)
    when (\&complicated_check) {
        say 'a complicated check for $n is true';
    }

    # match if no other cases match
    default {
        die q(I don't know what to do with $n);
    }
}

Loop>

The syntax for the loop-control operators is: last LABEL next LABEL redo LABEL goto LABEL A BLOCK by itself (labelled or not) is semantically equivalent to a loop that executes once. Thus, you can use last to leave the block or redo to restart the block. Note that this is not true of the blocks in eval {}, sub {}, or, much to everyone’s surprise, do {}. Loop controls don’t work in an if or unless, either, since those aren’t loops. But you can always introduce an extra set of braces to give yourself a bare block,
if (/pattern/) {{
    last if /alpha/;
    last if /beta/;
    last if /gamma/;
    # do something here only if still in if()
}}

The Ellipsis Statement

Perl accepts a bare ellipsis, “...” as a stub—that is, a place holder for code that you haven’t implemented yet.
sub unimplemented { ... }
eval { unimplemented() };
if ($@ =~ /Unimplemented/) {
    say "Caught an Unimplemented exception!";
}

Scope Declaration

Perl’s three scoping declarators make it easy to create completely private variables (using my or state), or to give selective access to global ones (using our). There is also a pseudodeclarator to provide temporary values to global variables (using local). These declarators are placed in front of the variable in question
my $nose;
our $House;
state $troopers = 0;
local $TV_channel;

Pragmas

use warnings;
# or explicitly enable warnings
...
{
no warnings;
# Disable warnings through end of block.
...
}
# Warnings are automatically enabled again here.

Perl 語言編程第四版筆記(零)


Chapter 1 An Overview of Perl


Manpage
Link
Covers
perl http://perldoc.perl.org/perl.html What perl manpages are available
perldata http://perldoc.perl.org/perldata.html Data types
perlsyn http://perldoc.perl.org/perlsyn.html Syntax
perlop http://perldoc.perl.org/perlop.html Operators and precedence
perlre http://perldoc.perl.org/perlre.html Regular expressions
prelvar http://perldoc.perl.org/perlvar.html Predefined variables
perlsub http://perldoc.perl.org/perlsub.html Subroutines
perlfunc http://perldoc.perl.org/perlfunc.html Built-in functions
perlmod http://perldoc.perl.org/perlmod.html How perl modules work
perlref http://perldoc.perl.org/perlref.html References
prelobj http://perldoc.perl.org/perlobj.html Objects
perlipc http://perldoc.perl.org/perlipc.html Interprocess communication
perlrun http://perldoc.perl.org/perlrun.html How to run Perl commands, plus switches
perldebug http://perldoc.perl.org/perldebug.html Debugging
perldiag http://perldoc.perl.org/perldiag.html Diagnostic messages


Manpage
Link
Covers
perlfaq1 http://perldoc.perl.org/perlfaq1.html General questions about Perl
perlfaq2 http://perldoc.perl.org/perlfaq2.html Obtaining and learning about Perl
perlfaq3 http://perldoc.perl.org/perlfaq3.html Programming tool s
perlfaq4 http://perldoc.perl.org/perlfaq4.html Data manipulation
perlfaq5 http://perldoc.perl.org/perlfaq5.html Files and formats
perlfaq6 http://perldoc.perl.org/perlfaq6.html Regular expressions
perlfaq7 http://perldoc.perl.org/perlfaq7.html General Perl language issues
perlfaq8 http://perldoc.perl.org/perlfaq8.html System interaction
perlfaq9 http://perldoc.perl.org/perlfaq9.html Networking

Chapter 2 bits and Pieces


print &lt<EOF;
The price is $Price.
EOF

print &lt&lt`EOC`;    # execute commands
echo hi there
echo lo there
EOC

print <<"dromedary", <<"camelid";    # you can stack them
I said bactrian.
dromedary
She said llama.
camelid


sub funkshun{
    say $_[0];
    say $_[2];
}

funkshun(<<"THIS", 23, <<'THAT');
Here's a line
or two.
THIS
And here's another.
THAT

Postfix


Introduction

簡單版
https://www.digitalocean.com/community/articles/how-to-install-and-setup-postfix-on-ubuntu-12-04

超級專業版
https://help.ubuntu.com/community/Postfix

Installation

$ sudo apt-get install postfix
$ sudo apt-get install mailutils


Configuration

/etc/postfix/main.cf 的內容
# 改成你的 hostname, 在安裝時應該就會主動抓到目前的 hostname, 所以不用修改
myhostname = pjack-VirtualBox
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
# 預設 mail server 在本地, 但如果有其他的 mail server, 請修改 mydestination
#mydestination = pjack-VirtualBox, localhost.localdomain, , localhost
mydestination = xxx.tw.yyy.org
# 預設是空的, 有需要可以加上去
relayhost = xxx-mailrelay.tw.yyy.org


Verification


不管執行那一種, 不久後應該就會收到信了!
# 第一種測試
$ echo "test content" | mail -s "test subject" pjack.chen@gmail.com

# 第二種測試
$ sendmail sample-email@example.org
hihi
^D

Agilefant

老闆透過這個在控制 product/project 的進行.

http://www.agilefant.org/

http://www.agilefant.org/wiki/download/attachments/98337/Agilefant+A4+Product+Tour.pdf

感覺還滿好用的, 而且是  open source, 真的有需要還可以自己 customize.





2013年5月23日 星期四

Intermediate Perl 筆記 (三)

Chapter 13 Introduction to Objects


use Cow;
use Horse;
use Sheep;
my @pasture = qw(Cow Cow Horse Sheep Sheep);
foreach my $beast (@pasture) {
    no strict 'refs';
    &{$beast."::speak"};   # Symbolic coderef, must turn off strict
}

foreach my $beast (@pasture) {
    $beast−>speak;         # use arrow invocation, no need to turn off strict
}

Class−>method(@args) 等價於 Class::method('Class', @args)
第一個參數會加上 "Class Name"
sub sound { 'baaaah' }
sub speak {
    my $class = shift;
    print "a $class goes ", $class−>sound, "!\n";
}


@ISA is an array, not a simple single value
use Animal;
our @ISA = qw(Animal);     # use @ISA to declare this class inherit from "Animal"
sub sound { "moooo" }

利用 parent 關鍵字來簡化宣告
use v5.10.1;
package Cow;
use parent qw(Animal);


要呼叫 parent declaration.
package Mouse;
use parent qw(Animal);
sub sound { 'squeak' }
sub speak {
   my $class = shift;
   $class−>Animal::speak(@_); # tell it where to start, but need to provide first argument
     $class−>SUPER::speak(@_);  # use SUPER keyword is ok too.
   print "[but you can barely hear it!]\n";
}



bless

http://stackoverflow.com/questions/392135/what-exactly-does-perls-bless-do

bless associates a reference with a package.
If the second argument is omitted, the current package/class is used.

package MyClass;
my $object = { };
bless $object, "MyClass";

sub new { 
  my $class = shift; 
  my $self = { }; 
  bless $self, $class; 
}



Chapter 14 Introduction to Testing


Skip first

Chapter 15 Objects with Data







Intermediate Perl 筆記 (二)

Chapter 6 Manipulating Complex Data Structures

Skip first

Chapter 7 Subroutine References


Anonymous Subroutines

my $ginger = sub {
    my $person = shift;
    print "Ginger: (in a sultry voice) Well hello, $person!\n";
};
$ginger−>('Skipper');

Returning a Subroutine from a Subroutine

sub create_find_callback_that_counts {
    my $count = 0;
    return sub { print ++$count, ": $File::Find::name\n" };
}

Closure Variables

利用 closure variable,可以實做出 function generator.
use File::Find;
sub print_bigger_than {
    my $minimum_size = shift;
    return sub { print "$File::Find::name\n" if −f and −s >= $minimum_size };
}

my $bigger_than_512 = print_bigger_than(512);
find($bigger_than_512, 'bin');

my $bigger_than_1024 = print_bigger_than(1024);
find($bigger_than_1024, 'bin');

The BEGIN keyword tells the Perl compiler that as soon as this block has been parsed successfully, jump for a moment to run phase and run the block as well.

BEGIN {
    my $countdown = 10;
    sub count_down { $countdown−− }
    sub count_remaining { $countdown }
}

Local static variable, "state" key word. The state variable has a limitation, though. So far, we can initialize only scalar variable swith state. We can declare other types of variables, but we can’t initialize them:

use v5.10;
sub countdown {
    state $countdown = 10;
    $countdown−−;
}

sub add_to_tab {
    state @castaways = qw(Ginger Mary Ann Gilligan); # compilation error
    state %tab = map { $_, 0 } @castaways; # compilation error
    $countdown{'main'}−−;
}


But, References are scalars, so we can initialize array or hash references.

use v5.10;
sub add_to_tab {
    my $castaway = shift;
    state $castaways = qw(Ginger Mary Ann Gilligan); # works!
    state %tab = map { $_, 0 } @$castaways; # works!
    $tab−>{$castaway}++;
}


Finding Out Who We Are

To get around this, v5.16 introduces the __SUB__ token to return a reference to the current subroutine

my $sub = sub {
    state $n = 5;
    return unless $n > -1;
    say $n--;
    __SUB__->();
};
$sub->();

Dump the function code

use v5.14;
use Data::Dump qw(dump);
use Data::Dump::Streamer;

my @luxuries = qw(Diamonds Furs Caviar);

my $hash = {
Gilligan        =>  sub {say 'Gilligan'},
Skipper         =>  sub {say 'SKipper'},
'Mr. Howell'    =>  sub {say 'Mr.Howell'},
Ginger          =>  sub {say $luxuries[rand @luxuries]},
};
Dump $hash;

The Output

my (@luxuries);
@luxuries = (
              'Diamonds',
              'Furs',
              'Caviar'
            );
$HASH1 = {
           Gilligan     => sub {
                             use strict 'refs';
                             BEGIN {
                               $^H{'feature_unicode'} = q(1);
                               $^H{'feature_say'} = q(1);
                               $^H{'feature_state'} = q(1);
                               $^H{'feature_switch'} = q(1);
                             }
                             say 'Gilligan';
                           },
           Ginger       => sub {
                             use strict 'refs';
                             BEGIN {
                               $^H{'feature_unicode'} = q(1);
                               $^H{'feature_say'} = q(1);
                               $^H{'feature_state'} = q(1);
                               $^H{'feature_switch'} = q(1);
                             }
                             say $luxuries[rand @luxuries];
                           },
           "Mr. Howell" => sub {
                             use strict 'refs';
                             BEGIN {
                               $^H{'feature_unicode'} = q(1);
                               $^H{'feature_say'} = q(1);
                               $^H{'feature_state'} = q(1);
                               $^H{'feature_switch'} = q(1);
                             }
                             say 'Mr.Howell';
                           },
           Skipper      => sub {
                             use strict 'refs';
                             BEGIN {
                               $^H{'feature_unicode'} = q(1);
                               $^H{'feature_say'} = q(1);
                               $^H{'feature_state'} = q(1);
                               $^H{'feature_switch'} = q(1);
                             }
                             say 'SKipper';
                           }
         };



Chapter 8 Filehandle References

Skip first

Chapter 9 Regular Expression References

Skip first

Chapter 10 Practical Reference Tricks

Skip first

Chapter 11 Building Larger Programs

Skip first

Chapter 12 Creating Your Own Perl Distribution

Skip first

Formatter in EPIC

Eclipse 內有 Formatter 的功能, 但 EPIC 預設的格式我不太喜歡, 在 perference 內可以設定的選項都不太符合我的需求,查了一下發現他是利用 PerlTidy 來做 formatter.

http://www.epic-ide.org/guide/ch02s04.php
http://stackoverflow.com/questions/3724257/how-to-format-perl-code


PerlTidy


Installation


以下的安裝除了裝 PerlTidy, 還有裝 Tidyview
$ sudo apt-get install libx11-dev
$ sudo apt-get install perltidy
$ sudo apt-get install perl-tk
$ sudo cpan install Tk
$ sudo cpan install TK::DiffText
$ wget http://prdownloads.sourceforge.net/perltidy/perltidy_20121207-1_all.deb
$ sudo dpkg -i perltidy_20121207-1_all.deb
$ wget http://sourceforge.net/projects/tidyview/files/latest/download -O tidyview.tar.gz
$ tar xzvf tidyview.tar.gz
$ cd tidyview*
$ cat README
To install this module, run the following commands:

    perl Makefile.PL
    make
    make test
    make install

DEPENDENCIES

Tk
Log::Log4perl
perltidy

$ perl Makefile.PL
$ make
$ make install

/etc/perltidyrc


之後就可以利用 tidyview 來找出你的要設定, 並且 output 成一個設定檔, 把它放到 /etc/perltidyrc


我的內容長這個樣子, 可以參考看看

# ON-OFF style options                                                                                                         
--break-after-all-operators
--no-break-before-all-operators
--no-closing-side-comments
--cuddled-else
--no-ignore-side-comment-lengths
--no-indent-closing-brace
--no-indent-spaced-block-comments
--no-line-up-parentheses
--no-outdent-long-comments
--no-outdent-long-quotes
--no-space-function-paren

# Numeric-value style options

--maximum-line-length=120

# Text-value style options


# Color options


# List-selection style options

--brace-tightness=2
--maximum-line-length=120
--paren-tightness=2
--paren-vertical-tightness=2
--square-bracket-tightness=2

# options not supported by tidyview


Configuration in EPIC


其實放到 /etc/perltidyrc 後, EPIC 就會自動讀取這個檔案, 但我發現 EPIC 會主動加上 --maximum-line-length=80, 導致我在設定檔內的設定失效. 所以如果遇到這個狀況, 我的解決方式是在 EPIC 內多加上一個 -l=120,





2013年5月13日 星期一

Intermediate Perl 筆記 (一)

Chapter 2 Using Modules


use lib '/Users/gilligan/lib';

The use lib indeed runs at compile time, so this also doesn’t work
my $LIB_DIR = '/Users/gilligan/lib';
...
use lib $LIB_DIR;    # BROKEN
use Navigation::SeatOfPants;

Fix it with "use constant"

use constant LIB_DIR => '/Users/gilligan/lib';
...
use lib LIB_DIR;
use Navigation::SeatOfPants;

Setting the Path Outside the program


solution 1: using global variable
export PERL5LIB=/home/skipper/perl−lib

solution 2: assign include path on the command line
% perl −I/home/skipper/perl−lib /home/skipper/bin/get_us_home


Chapter 3 Intermediate Foundations

List Operation

my @input_numbers = (1, 2, 4, 8, 16, 32, 64);
my @result = map $_ + 100, @input_numbers;          # output 101, 102, 104, ...
my @result = map { $_, 3 * $_ } @input_numbers;     # output 1, 3, 2, 6, 4, 12, ...
my %hash = map { $_, 3 * $_ } @input_numbers;       # output hash { 1=>3, 2=> 6, ...}

Dereferencing the Array Reference


@ skipper                   # refer to the array
@{ $ref_skipper }           # refer to the array by reference
@$ref_skipper               # getting braces off if it is a simple scalar variable

Checking Reference Types



use Carp qw(croak);
sub show_hash {
    my $hash_ref = shift;
    my $ref_type = ref $hash_ref;
    croak "I expected a hash reference!" unless $ref_type eq 'HASH';
    croak "I expected a hash reference!" unless $ref_type eq ref {};   # another way

    foreach my $key ( %$hash_ref ) {
        ...
    }
}

# another way to accepts all objects that support "keys" function, not only hash object

use Scalar::Util qw(reftype);
sub show_hash2 {
    my $hash_ref = shift;
    my $ref_type = reftype $hash_ref; # works with objects
    croak "I expected a hash reference!" unless eval { keys %$ref_type; 1 };
    foreach my $key ( %$hash_ref ) {
        ...
    }
}


Chapter 5 References and Scoping


Nothing noted.

2013年5月9日 星期四

System-wide environment variables in Ubuntu


要怎麼新增一個 system-wide global environment 可參考以下這篇

https://help.ubuntu.com/community/EnvironmentVariables

  • /etc/environment - This file is specifically meant for system-wide environment variable settings. It is not a script file, but rather consists of assignment expressions, one per line. Specifically, this file stores the system-wide locale and path settings.
Not recommended:
  • /etc/profile - This file gets executed whenever a bash login shell is entered (e.g. when logging in from the console or over ssh), as well as by the DisplayManager when the desktop session loads. This is probably the file you will get referred to when asking veteran UNIX system administrators about environment variables. In Ubuntu, however, this file does little more than invoke the /etc/bash.bashrc file.
  • /etc/bash.bashrc - This is the system-wide version of the ~/.bashrc file. Ubuntu is configured by default to execute this file whenever a user enters a shell or the desktop environment.


如果加在 /etc/bash.bashrc 內, sudo xxxx, 的時候不會發揮作用, 因為沒有真的 login
有些時候希望sudoer 能繼承自己的 local variable, 可以使用以下方式, 把 env_reset 換成 env_keep

# This file MUST be edited with the 'visudo' command as root.
#
# See the man page for details on how to write a sudoers file.
#

#Defaults       env_reset
Defaults        env_keep+="PERL5LIB"

2013年5月5日 星期日

Perl 學習手冊第六版筆記(五)

Chapter 14 Strings and Sorting


String Functions


index, rindex, substr, sprintf,

String & Number Compare


sub by_number { $a <=> $b }
sub by_code_point { $a cmp $b }

Chapter 15 Smart Matching


http://perldoc.perl.org/perlsyn.html

use 5.010001;
say "I found a key matching 'Fred'" if %names ~~ /Fred/;

say "The arrays have the same elements!"
if @names1 ~~ @names2;

Example
Type of match
%a ~~ %b
hash keys identical
%a ~~ @b or @a ~~ %b
at least one key in %a is in @b
%a ~~ /Fred/ or /Fred/ ~~ %b
at least one key matches pattern
'Fred' ~~ %a
exists $a{Fred}
@a ~~ @b
arrays are the same
@a ~~ /Fred/
at least one element in @a matches pattern
$name ~~ undef
$name is not defined
$name ~~ /Fred/
pattern match
123 ~~ ’123.0’
numeric equality with “numish” string
’Fred’ ~~ ’Fred’
string equality
123 ~~ 456
numeric equality

The given Statement


Don't need to type "break" for each case. But you can add "continue", Perl tries next condition.

given ( $ARGV[0] ) {
    when ( 'Fred' )     {say 'Name is Fred' }
    when ( /fred/i )    {say 'Name has fred in it' }
    when ( /\AFred/ )   {say 'Name starts with Fred' }
    default             {say "I don't see a Fred" }
}


foreach ( @names ) { # don't use a named variable!
    when ( /fred/i )  { say 'Name has fred in it'; continue }
    when ( /\AFred/ ) { say 'Name starts with Fred'; continue }
    when ( 'Fred' )   { say 'Name is Fred'; }
    default           {say "I don't see a Fred" }
}


Chapter 16 Process Management


The system Function


system 'date';
exec 'date';
my $now = `date`;
my $output = qx(echo $$);
my $output = qx'echo $$';
my @who_lines = `who`;    #automatically get the data broken up by lines

Processes as File Handles


Pipe goes before or after the command that you want to run.
If you want a read filehandle, you use -|, and if you want a write filehandle, you use |- to show which side of the pipe you want to place the command.


open DATE, 'date|' or die "cannot pipe from date: $!";              # same as  date | my_program
open MAIL, '|mail merlyn' or die "cannot pipe to mail: $!";         # same as  my_program | mail merlyn
open my $date_fh, '-|', 'date' or die "cannot pipe from date: $!";
open my $mail_fh, '|-', 'mail merlyn' or die "cannot pipe to mail: $!";


Getting Down and Dirty with Fork

http://perldoc.perl.org/perlipc.html

Sending and Receiving Signals


Some Advanced Perl Techniques

Slices

#### Array Slice ########
my @names = qw{ zero one two three four five six seven eight nine };
my @numbers = ( @names )[ 9, 0, 2, 1, 0 ];
print "Bedrock @numbers\n"; # says Bedrock nine zero two one zero

#### Hash Slice ########
my @three_scores = ($score{"barney"}, $score{"fred"}, $score{"dino"});
my @three_scores = @score{ qw/ barney fred dino/ };


Trapping Errors

eval


As soon as the eval encounters a normally fatal error, it stops the entire block and continues with the rest
of the program. Notice that semicolon after the eval block. The return value of the eval is the last evaluated expression, just like a subroutine. If the eval caught a fatal error, it returns undef and puts the error
message in the $@ special variable, perhaps something like: Illegal division by zero
at my_program line 12.

my $barney = eval { $fred / $dino } // 'NaN';
if ($@) {
    print "An error occurred ($@), continuing\n";
}

Try::Tiny


use 5.010;
my $barney =
    try { 
        $fred / $dino 
    } catch {
        say "Error was $_"; # not $@
    } finally {
        say @_ ? 'There was an error' : 'Everything worked';
    };

autodie


use autodie;
open my $fh, '<', $filename; # still dies on error
Combine with Try:Tiny
se 5.010;
use autodie;
use Try::Tiny;
try {
    open my $fh, '<', $filename; # still dies on error
} catch {
    when( 'open' ) { say 'Got an open error' }
};

grep

my @odd_numbers = grep { $_ % 2 } 1..1000;

map

my @data = (4.75, 1.5, 2, 1234, 6.9456, 12345678.9, 29.95);
my @formatted_data = map { &big_money($_) } @data;

List::Util & List::MoreUtils

use List::Util qw(first);
my $first_match = first { /\bPebbles\b/i } @characters;

use List::Util qw(sum);
my $total = sum( 1..1000 ); # 500500

use List::Util qw(max);
my $max = max( 3, 5, 10, 4, 6 );

use List::Util qw(maxstr);
my $max = maxstr( @strings );

use List::Util qw(shuffle);
my @shuffled = shuffle(1..1000); # randomized order of elements

use List::MoreUtils qw(none any all);
if (none { $_ > 100 } @numbers) {
    print "No elements over 100\n"
} elsif (any { $_ > 50 } @numbers) {
    print "Some elements over 50\n";
} elsif (all { $_ < 10 } @numbers) {
    print "All elements are less than 10\n";
}

use List::MoreUtils qw(natatime);
my $iterator = natatime 3, @array;
while( my @triad = $iterator->() ) {
    print "Got @triad\n";
}

use List::MoreUtils qw(mesh);
my @abc = 'a' .. 'z';
my @numbers = 1 .. 20;
my @dinosaurs = qw( dino );
my @large_array = mesh @abc, @numbers, @dinosaurs;