Enhancing Skills

perl: Practical Extraction and Report Language

The perl command is a powerful programming language used for text processing, system administration, web development, and more. It provides extensive capabilities for string manipulation, file handling, and regular expressions.

Command:

perl [options] [program| -e 'program'] [arguments...]

Examples

  1. Simple Print Statement
   perl -e 'print "Hello, World!\n";'

Description: Executes a Perl script that prints “Hello, World!” to the console.

Sample Output:

   Hello, World!
  1. Substitute Text in a File
   perl -pi -e 's/old/new/g' filename.txt

Description: Replaces all occurrences of “old” with “new” in filename.txt in place (-i option).

Sample File (filename.txt):

   This old text is old.

Sample Output in filename.txt:

   This new text is new.
  1. Print Lines Matching a Pattern
   perl -ne 'print if /pattern/' filename.txt

Description: Prints lines from filename.txt that match the pattern “pattern”.

Sample File (filename.txt):

   Line 1
   Line with pattern
   Line 3

Sample Output:

   Line with pattern
  1. Count Occurrences of a Word
   perl -ne '$count++ while /word/g; END { print "$count\n"; }' filename.txt

Description: Counts occurrences of the word “word” in filename.txt and prints the count.

Sample File (filename.txt):

   word word
   another word

Sample Output:

   3
  1. Extract Specific Columns from a File
   perl -F',' -lane 'print $F[1]' filename.csv

Description: Extracts and prints the second column from a CSV file filename.csv, assuming comma as the delimiter.

Sample File (filename.csv):

   col1,col2,col3
   data1,data2,data3

Sample Output:

   col2
   data2
  1. Convert Text to Uppercase
   perl -pe '$_ = uc($_);' filename.txt

Description: Converts all text in filename.txt to uppercase.

Sample File (filename.txt):

   some lowercase text

Sample Output:

   SOME LOWERCASE TEXT
  1. Read and Modify JSON Data
   perl -MJSON -ne 'print encode_json(decode_json($_)->{key})' file.json

Description: Reads file.json, decodes it, extracts the value for “key”, and prints it as JSON.

Sample File (file.json):

   {"key": "value"}

Sample Output:

   "value"

The perl command is highly versatile and powerful, making it suitable for a wide range of tasks from quick one-liners to complex scripts.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.