Use Perl to split string instead of awk
Answer:
If you know Perl well, there is no need to use awk to do string processing such as string splitting, it is easy with Perl also, e.g.
# echo "foo,bar,k3" | perl -F',' -lane 'print $F[1]'
bar
Linux Ask! is a Q & A web site specific for Linux related questions. Questions are collected, answered and audited by experienced Linux users.
Use Perl to split string instead of awk
Answer:
If you know Perl well, there is no need to use awk to do string processing such as string splitting, it is easy with Perl also, e.g.
# echo "foo,bar,k3" | perl -F',' -lane 'print $F[1]'
bar
Print to standard output in different scripting languages
Answer:
To print a string of "Hello World" to the standard output in different scripting languages
1. Perl
print "Hello, World!";
2. Python
print('Hello, World!')
3. PHP
echo "Hello, World!";
4. Ruby
puts "Hello, World!"
Enable Perl strict mode to restrict unsafe constructs
Answer:
In Perl, you can enforce using the strict mode to reduce the chance of nasty error, e.g.
$foo = 'bar';
print $foo;
If you run the above problem, it is completely valid.
# perl test.pl
bar
However, if you use the strict pragma
use strict;
$foo = 'bar';
print $foo;
And run the program again..
# perl test.pl
Global symbol "$foo" requires explicit package name at test.pl line 3.
Global symbol "$foo" requires explicit package name at test.pl line 4.
Execution of test.pl aborted due to compilation errors.
Since the $foo is not declared before the first use, so the compilation stopped. In modern Perl developements, it is recommended to alwasys use the strict pragma in order to write a better and maintainable program.
To fix the problem, you need to use the my keyword, e.g.
use strict;
my $foo = 'bar';
print $foo;
And run the program again. (Thanks Jeroen for the suggestion)
Multi-line string in Perl
Answer:
To assign a multi-line string to a variable in Perl, is easy with the following trick:
my $html = <<END;
<p>
This is HTML content.
</p>
END
print $html;
How can I find out my current package in Perl?
Answer:
To find the current package in your Perl script, you can try something like the following:
package Foo;
my $current_package = __PACKAGE__;
print "I am in package $current_package\n";
1;
When executed:
# perl foo.pl
I am in package Foo