Saturday, January 1, 2011

One-liners in perl

# at the command line, type each line after the '>'
# and you'll get the output that
# follows it

# print the @ARGV contents with no program arguments
> perl -MData::Dumper -e'print Dumper \@ARGV'
$VAR1 = [];

# print the @ARGV contents with arguments "a" and "b"
> perl -MData::Dumper -e'print Dumper \@ARGV' a b
$VAR1 = [
          'a',
          'b'
        ];

# print the @ARGV contents with warnings on, and arguments "a" and "b"
> perl -w -MData::Dumper -e'print Dumper \@ARGV' a b
$VAR1 = [
          'a',
          'b'
        ];

# print the @ARGV contents with arguments "a", "b", and "-w"

# note how the -w is not stolen by Perl if it follows arguments
# that Perl knows it doesn't want

> perl -MData::Dumper -e'print Dumper \@ARGV' a b -w
$VAR1 = [
          'a',
          'b',
          '-w'
        ];
Here is the final line that includes some <angle brackets>




# print the Perl process ID, followed by a newline
> perl -e'print "$$\n"'
2063

# error: the first two double quotes go together, the rest is passed
# to the script directly

> perl -e"print "$$\n""
Bareword found where operator expected at -e line 1, near "1895n"
        (Missing operator before n?)
syntax error at -e line 1, next token ???

Execution of -e aborted due to compilation errors.



Cleanliness

-w    turn warnings on
-Mstrict    turn the strict pragma on

Data
-0     (that's a zero) specify the input record separator
-a     split data into an array named @F
-F      specify pattern for -a to use when splitting
-i      edit files in place (see perldoc perlrun for the many details)
-n      run through all the @ARGV arguments as files, one by one, using <>
-p      same as -n, but will also print the contents of $_

Execution control
-e      specify a string to execute as a script (multiples add up)
-M    import a module
-I      specify directories to search for modules before standard places

   

   

  

No comments: