Showing posts with label Script. Show all posts
Showing posts with label Script. Show all posts

Thursday, March 13, 2008

Ruby VS Python: The discussion

It turned out that the discussion about ruby & python is quite big nowadays. And here is a deep talk about them, before you click on it, I should warn you that it is VERY LONG : http://lambda-the-ultimate.org/node/1480 And there's even a meeting in Europe called RuPy Have fun programming, everybody!

Thursday, March 6, 2008

Learning Perl, 4th Edition Notes 0x9

Learning Perl, 4th Edition Notes 0x9 by DaNmarner * Compared to the traditional if control structure, unless works in the opposite way, which is equal to if (!condition) {} , else is conditional in this structure. * until structure function as while (!condition ) * if, unless, while, until, foreach can be used as expression modifiers. Thus, a statement can be written in reverse. The limitation for this is, only one expression is allowed on either side of the modifiers. * elsif equals to "else if" in if structure. * Autoincrement/decrement operator (++,--) is the same as them in C. * for loop, like in C, is available in perl, too. * last, as "break" in C, stops the loop's execution. Similarly, next ends the current iteration. * redo repeats current iteration in a loop. * last, next and redo can work with lables to effect the outer loop. The syntax is, say, when used in a while loop nested in a unless loop:
LABLENAME: unless { while { redo LABLENAME; } }
* The value of logical operator "&&" and "||" is the last evaluated part. And they could be written in words ("and", "or"). * The ternary operator (?:), as it in C, is availble in perl.

Sunday, February 24, 2008

Learning Perl, 4th Edition Notes 0x8

Learning Perl, 4th Edition Notes 0x8 by DaNmarner * The operator "s///" substitutes the part of variable that matches with the pattern between the first two slashes with the stuff between the last two slashes, and returns a boolean value to tell whether the substitution is successful. * Putting a "g" after "s///" makes it operate on all the parts that can be matched in the variable, instead of just one. * Like "m//", the delimiter in "s///" is variable from different characters, either paired or nonpaired. Same thing happens to the other matching modifiers like /i, /x and /s. So is to the binding operator (=~). * Case shifting works on the replacement word: \U forces whatever following it to be uppercase, while for \L, lowercase. The effects of the two guys above could be turned off by \E. \u and \l work on only one letter that follows them. * Case shiftint works not only on part of the "s///", but also in all the double quoted strings. * Yielding a list, the split operator seperates a scalar of string by its given seperator:
@list = split /seperator/, $string;
* Yielding a scalar, the join operator glues a list of strings with the given glue string between the pieces:
$scalar = join $glue_string, @list;
* Used in a list context, the "m//" operator returns a list of matching variables created with the parentheses withing the pattern. * To make the quantifiers non-greedy, put a qustion mark (?) after them. * The modifer "m" changes the "m//" and "s///" operator into operating each line within a variable, instead of the whole variable. * By default, the value of $^I is undef. But when it is assigned with any string, that string will become the suffix of the backup of the files that are read in via the diamond operator and modified. When this happens, the default output is changed into those files from the standard output. * The code operating on a serial of files
#!/usr/bin/perl # Part 1 $^I = ".bak"; # Part 2 while( <> ) { # Part 3 s/Randal\ the\ grey/"Randal the white"/g; # Part 4 print; # Part 3 } #Part 3
is equivalent to the following in command line:
$ perl -p -i.bak -e 's/Randal\ the\ grey/"Randal the white"/g' The_serial_of_files
As the comments show, the arguments in the command line contributes to differnt parts in the code. To clarify, part 1-4 are each contributed by "perl", "-i.bak", "-p", "-e ...". This is hard to put shortly, but in addtion, using -n instead of -p will take the "print" line out of the code and leave other things the same. * There's a way to group things in Regular Expression without triggering the memory variables. To achieve this, lead whatever is grouped with "?:".

Learning Perl, 4th Edition Notes 0x7

Learning Perl, 4th Edition Notes 0x7 by DaNmarner * Patterns-in-paired-forward-slashes is actually a shortcut of "m / pattern /". The delimiers could be chosen from other nonpaired characters or some paired characters. * Modifiers, or flags, can change a regular expression's behavior from the default. They are appended as a group right after a regular expression. To be specific: i makes the matching case-insensitive; s makes dot matches any character, even newline (\n); x allows you to add spaces to a pattern to make it look better. * Anchors hold the matching at a particular point instead of floating around the whole string. Amount which: carats (^) mark the beginning; dollar signs ($) mark the end; \b marks either end of a word; \B is the opposit of \b; * The binding charater, defined as "=~", tells perl to match the pattern on the left against the string on the left. * Patterns are intepolatable in double quoted strings. * In a pattern, Perl stores the part that the n th set of paratheses match into $n. These so-called match variables stay around until the next time a pattern match successfully. * Eventually a string matched by a pattern is divided into at least three parts, which are stored automatically by perl in to the variable names followed by their description below: the part that the pattern matches ($&); the part that leads the first part ($`); the part that succeeds the first part ($'); * The syntax for the more general quantifiers are pairs of curl braces following the quantified item, within which is the number(s) of the repeated time. There can be only one number that indicates the exact quantity, or two numbers seperated by a comma that tell the range of the quantity. In the seconed case, the seconed number is optional, leaving it blank indicates that there's no upper limit to the quantity. * The high-to-low precedence of the metacharacters in a pattern is briefely: grouping parentheses, quantifiers, anchors and sequence, vertical bars. * Further info about regular information in Perl can be found in perlre, perlrequick and perlretut manpages.

Thursday, February 21, 2008

Learning Perl, 4th Edition Notes 0x6

Learning Perl, 4th Edition Notes 0x6 by DaNmarner * The support for regular expressions (patterns) in perl allows fast, flexible and reliable string handling. * Some considered Regular Expression, whose function is to judge whether a string matches the template it stands for or not, a simple programming language. * Pattern is match is generally being used to return a true or false value. It's almost always found in if or while structure. * Some characters have special meanings in regular expression. These characters are named metacharacter. When matching them as a literal character, put backslash before them. * Metacharacter dot (.) matches any single character except a new line. Backslash itself is a metacharacter, too. * Use quantifiers when the quantitiy of the preceding item needs to be specified in a regular expression. A question mark (?) means the preceding item occurs 0 or 1 time. The plus (+) quantifier means 1 or more, while the star (*) means both. * Parentheses are the metacharacters that group the stuff. * The vertical bar (|) means "or". * A list of possible characters inside square brackers ([]) is called a character class. Which matches any single characters from within the class. * Hyphen (-) specifiys a range of characters in character classes. * A caret (^) at the start of a character class negates it. * Several character class shortcuts: d leaded by a backslash stands for [0-9], while w for [A-Za-z0-9_] and s for [\f\t\n\r ]. To negate them, use capital letters instead.

Wednesday, February 20, 2008

Learning Perl, 4th Edition Notes 0x5

Learning Perl, 4th Edition Notes 0x5 by DaNmarner * hash is the data structure that stores the key/value data pairs without order. * Syntax to access a hash element:
$hash_name{$key}
* Accessing an unassigned hash element will yield undef. * Hash name is leaded by a percent sign (%) when treated as a variable, like the at sign (@) for arrays. * In a list context, hash appears as a list that consist of key/value pairs in a random sequence. * To switch kay and value in hashs, use reverse:

%a_hash = reverse %a_hash;

* For convenience, the big arrow (=>) can be used to show the relation between kay and value in literal hashs.

$a_hash = ( "localhost" => '172.0.0.1', );
* the key function returns a key list of a hash, while the the values function returns the values. * The each function can be used to iterate a hash, it returns a list consists of two elements each time it is used: a pair of kay/value. * The existence of a key can be tested by the function exists. * delete function will make a key disappear, but not assign undef to it.

Monday, February 18, 2008

Learning Perl, 4th Edition Notes 0x4

Learning Perl, 4th Edition Notes 0x4 by DaNmarner * If <STDIN> encounters an end-of-file, it returns undef, which is handy when it is used as a while condition:
while (<STDIN>) { print; }
* while reads a line and start an iteration each time. In contrast, foreach dosen't start the loop until it read the whole thing. * The diamond operator (<>) reads in the files listed in invocation arguments, and returns a list. * The invocation arguments are automatically stored in the array @ARGV. * When printing an interpolated array, there will be spaces between each elements. * A C-like printf is available in perl, which requires a format string and a list of things to print. * A trick to print arrays with printf:
$format_string = "something first".("%s " x @the_array_to_be_printed); printf $format_string, @the_array_to_be_printed;
* A filehandle is the name in a Perl program for an I/O connection between Perl process and the outside world. * A Perl process automatically inherits, at least, three filehandles from its parent process when starts: STDIN, STDOUT, STDERR. * To open a filehandle, use open, followed by the filehandle name and a double quoted file name:
open NAME, "file_name";
The file name can be leaded by ">", "<" or ">>", which stands for overwrite, read from or add to a file. Another way to do this it to use three arguements:
open NAME,">>",$file_name;
* open will return a false value if it opens a "bad" filehandle. * To close a filehand, use close to lead the filehandle name. * die accepts a string to print out into STDERR before it ends the process. It also stores the error message given by the system into $!; * worn works in the same way as die, but it dosen't quit the program. * A filehandle name following print or printf will change the latters desination. * select changes the default output filehandle:
select FILEHAND;
* If a filehandle is reopened, the original one will be hang up, and will return when the new one terminates.

Thursday, February 7, 2008

Learning Perl, 4th Edition Notes 0x3

Learning Perl, 4th Edition Notes 0x3 by DaNmarner * In Perl, a "function" indicates either a Perl build-in function or a user-defined function, while a "subroutine" means only the latter. * The defination of a subroutine includes a keyword "sub", followed by the function name and then the code block enclosed by curly braces. * To invoke a subroutine, use ampersand (&) before the function name. * Besides the use of "return", Perl automatically treats the last performed calculation as the return value. * Perl saves the parameters list in the private array @_, * Excess parameters as well as the insuffient ones, will be ignored. in the second case, undef will fill in the blank arguments. * All variables are defaulely globle unless the operator "my" is used. "my" makes a varable lexical. This works not only in functions but also in code blocks. * The "use strict" prama will force the declaration of every new variable to be coded. * If a subroutine is defined before its invocation, or it is invoked with arguments, and its name doesn't conficts with a build-in function, the ampersand can be omitted. * A "return" with nothing followed will make the subroutine return undef. * Not only scalars can be the return value.

Tuesday, February 5, 2008

Learning Perl, 4th Edition Notes 0x2

Learning Perl, 4th Edition Notes 0x2 by DaNmarner

* Lists, which means ordered collections of scalars, are often used as if it is interchangeable with arrays, while the latter are actually the data structure, which, worthy enough to be pointed out to those C programmers, are considered as variables. * Numbers, strings and undef values can be held in a same array. * The syntax for refering an array is

@array_names
while the way to access an elements is usually $array_names[index] * The array is automatically extended as needed. The following code
$a_array[0] = 'the value'; $a_array[100] = 'the end value';
creates 99 array elements whose value is undef. * A list literal is a list of comma-separated values enclosed with parentheses. ".." is a range operator. It creates a list of values by counting from the left scalar, which must be smaller than the latter, up to the right ones. * A great shortcut to generate a list of simple words is to use qw. Which saves the quotes marks and commas. Whitespaces between words are discarded. Any punctuation character can be used as the delimiter instead of parentheses. Put a backslash before the delimiter when it appears in the list. * List assignment is applied by using, not surprisingly, the equal character.
list_one = list_two.
The list can be either arrays or list literals. * Using arrays as stacks, pop and push operator works on the last elements of an array.
$scalar = pop @an_array; # take the last elements off and return it. push @an_array,@another_array; # add the second array(which can also be a scalar) to the end of the first one.
* shift operator takes off the first element of an array and return its value. unshift do the opposite thing. * Arrays may be interpolated into space-separated string in a double quoted string. * Syntax of foreach control structure:
foreach $iterate_scalar ( iterated_list ) { code block; }
When the iterate scalar is omitted, the default $_ will be there instead. * The reverse operator reverses the order the elements in a list. * The sort operator sorts the elements of a list into dictionary order * reverse operator generates a scalar when used in scalar context. * A scalar is automatically promoted to make a one-element list in list context. * to force a scalar context: put scalar before the array. * returns the rest of input in list context. * chomp used on an array removes all the ending newline characters in each elements.

Thursday, January 31, 2008

Learning Perl, 4th Edition Notes 0x1

Learning Perl, 4th Edition Notes 0x1 by DaNmarner * Perl computes with double-precision floating-point values. * Octal (base 8) is leaded by 0, while hexadecimal leaded by 0x and binary 0b. * For clarity, underscore within integer literals is available. So is for non-decimal literals. * Use perl string to create, scan, and manipulate raw binary data. * Unlike in double quote, any characters other than a single quote or a backslash between the single quote marks stands for itself inside a string. * Numeric Operater: +-*/% String Operater: .x * Using Build-In Warnings Turn on in command line:
$perl -w program
or, for more details:
$perl -Mdiagnostics ./program
Request on #! line:
#!/usr/bin/perl use progma
#!/usr/bin/perl use warnings;
or, for more details:
#!/usr/bin/perl use digonostics;
* Output with print
print list;
list is a series of scalars seperated by commas. * Double-quoted string literal is subject to variable interpolation. Curly braces can be used as the delimiter of variable names. For instance:
print "This is $whats"; #print the value of $whats print "This is ${what}s" #print the value of $what
* Perl has the same precedence and associativity as C. * Numeric and string comparison operators: == eq (equel) != ne (not equel) <> gt (greater than) <= le (less or equel) >= ge (greater or equel) * For boolean values, 0 or empty string means false, other number or string means true; * reads the next complete text line from standard input. New line included. * Use chomp to remove the newline character from a string, common used like this: chomp ($line=); * The value undef exists in those unassigned variables. returns undef is there's no more input is there(end-of-file or Ctrl+D).

Learning Perl, 4th Edition Notes 0x0

Learning Perl, 4th Edition Notes 0x0 by DaNmarner This series, hopefully will last for a while, is the notes that I take down from the book Learning Perl, 4th Edition, by Randal L. Schwartz, Tom Phoenix, and Brian D Foy. I've known C for several years and I'm starting learning perl, about which people say that it is a powerful and efficient tool for many uses. My study environment is Ubuntu Linux 7.10, bash, perl 5.8.8. The notes will follow the sequence of the chapters in the book. It will contain the main knowledge points in the book that is new to me. Thus, those stuff that is similar to C will probably be ignored. I hope these notes will benefit somebody besides me. Suggestions, criticisms, additions, corrections and discussions are welcomed anytime!

Thursday, January 3, 2008

Read CHM file with Firefox in Linux

With several steps done,I made myself able to read chm files with Firefox in Ubuntu.
  1. Add the extension CHM Reader
  2. Save the following shell script as readchm.sh (or any other name you like) to /usr/local/bin (or any place you like).

    #!/bin/sh

    firefox "chm:file:///$1"

    exit 0

  3. Change the script to excutable file:
    chmod 755 /usr/local/bin/readchm.sh
  4. Right click a chm file,choose "Open with another Appication",click "Usa a custom command",type in
    /usr/local/bin/readchm.sh
  5. Click "Open".
Note:By default,you will find that the table of content is missing in firefox,you can get it by clicking View-Sidebar-CHM Reader.