PERL BASICS
LINUX
&
BY:- SAGAR KUMAR
Introduction to Linux
o Open source Operating System
o Developed by Linus Torvalds
o Architecture of Linux operating system
Linux Basic Commands:
o SYSTEM & HARDWARE INFORMATION
o USER INFORMATION AND MANAGEMENT
o FILE AND DIRECTORY COMMANDS
o PROCESS MANAGEMENT
o FILE PERMISSIONS
o NETWORKING
o ARCHIVES (TAR FILES)
o SEARCH
o FILE TRANSFERS
o DIRECTORY NAVIGATION
System & Hardware Information:-
o uname –a #Display Linux system information
Linux aa34faf8af0b 3.10.0514.26.2.el7.x86_64 #1 SMP Tue Jul 4 15:04:05 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
o uname –r #Dispaly kernel release information
3.10.0-514.26.2.el7.x86_64
o uptime #for how long system has been running
11:56:15 up 14 days, 21:18, 0 users, load average: 23.14, 24.23, 24.68
o hostname #gives hostname of the system
cb.vu
o hostname –I #gives IP address of the Host
78.31.70.238
o last reboot #to check when the system has been last rebooted
wtmp begins Sat Sep 9 10:24:23 2017
o date #display the date and time
Mon Jan 01 2018 17:17:33 GMT+0530 (India Standard Time)
o cal #display current month calendar
o free #Display the free and used memory (-h for human readable, -m for MB, -g for GB)
total used free shared buff/cache available
Mem: 263861664 11205028 205258364 1867876 47398272 233338992
Swap: 4194300 1756284 2438016
User Information and Management:-
o w #show who is logged in and what they are doing.
12:07:00 up 14 days, 21:29, 0 users, load average: 21.66, 24.14, 24.30
USER TTY LOGIN@ IDLE JCPU PCPU WHAT
o who #who is logged into the system
o whoami #who are you logged in as
[2018-01-01 17:41.43] ~
[SAGAR.workgroup] ➤ whoami
SAGAR
o id #display the current user id and group id
[2018-01-01 17:41.49] ~
[SAGAR.workgroup] ➤ id
uid=1001(SAGAR) gid=513(UsersGrp) groups=1002(HomeUsers),1004(ORA_DBA),559(Performance Log Users),545(Users)
o last #who logged in last
Files and Directories Commands:
o ls –al #lists all file in long listed format
o ll #actually aliased to `ls -l'
o pwd #shows present working directory
o mkdir directory_name #creates a new directory
o rmdir directory_name #deletes an empty directory
o rm –r directory_name #deletes the directory and its contents
o rm filename #deletes a file
o cp file1 file2 #copy one file to another
o mv file1 file2 #move a file/ rename a file
o touch filename #create a new file
o cat filename #displays the file contents
File Permissions:
• There are 3 types of users
1. User(u) 2. Group(g) 3. Others/ World(o)
• Below are the permissions types
• Read= r
• Write= w
• Execute = x
• No access = -
• Commands to change the permissions of the file:- chmod
example:- chmod 755 filename
1/0 1/0 1/0
r = - - -
w = - - -
x = - - -
Example: rwx rwx rwx chmod 777 filename
Archives (Tar files):
o tar -cf archive.tar directory # Create tar named archive.tar containing directory.
o tar -xf archive.tar # Extract the contents from archive.tar.
o tar -czf archive.tar.gz directory # Create a gzip compressed tar file name archive.tar.gz.
o tar -xzf archive.tar.gz # Extract a gzip compressed tar file.
Directory Navigation:
o cd .. # To go up one level of the directory tree. (Change into the parent directory.)
o cd # Go to the $HOME directory
o cd /etc # Change to the /etc directory
o cd - # go back to previous directory (last accessed dir)
Process Management:
o ps #your currently running processes
o ps –ef #all the currently running processes on the system
o ps- -ef |grep processname #process information for process name
o kill pid #kill a process
o top #display and manage the top processes
o killall processname #kill all processes named there
o program & #start program in the background
o bg #display stopped or background processes
o fg #bring the most recent backgroungd job to foreground
Networking:
o ifconfig #Displays network interface and ip address
o ping #to check given address is alive or not
o dig domain_name #display DNS information for domain
o dig –x IP_Address #Reverse lookup of IP_Address
o host domain #display DNS IP address for domain
o hostname #display the hostname
[2018-01-01 19:06.49] ~
[SAGAR.workgroup] ➤ hostname
workgroup
o netstat #Display listening tcp and udp ports and corresponding programs
[2018-01-01 19:11.20] ~
[SAGAR.workgroup] ➤ netstat
Active Connections
Proto Local Address Foreign Address State
TCP 10.10.156.9:4280 hk2sch130022025:https ESTABLISHED
TCP 10.10.156.9:4294 sb-in-f188:5228 ESTABLISHED
TCP 10.10.156.9:6010 static:https ESTABLISHED
TCP 10.10.156.9:9327 static:https ESTABLISHED
TCP 10.10.156.9:9635 13.75.42.223:https TIME_WAIT
SEARCH:
o grep pattern file # Search for pattern in file
o grep -r pattern directory # Search recursively for pattern in directory
o locate name # Find files and directories by name
o find /home/Dir -name 'prefix*’ # Find files in /home/Dir that start with "prefix".
o find /home -size +100M # Find files larger than 100MB in /home
File Transfer:
o scp file.txt server:/tmp # Secure copy file.txt to the /tmp folder on server
o scp server:/var/www/*.html /tmp # Copy *.html files from server to the local /tmp folder.
o scp -r server:/var/www /tmp # Copy all files and directories recursively from server
to the current system's /tmp folder.
File Editing:
o Most common editor in Linux -- vi editor
o Commands for editing files in vi editor
o vi filename # to open file in editor (Command mode)
o Press “i” # to go in INSERT mode
o double esc # moving to command mode
o :w #to save changes
o :q #to exit
o :q! #force exit
o :wq #save changes and exit
o Commands for movement inside a file
o h, j, k ,l #left, down, up
o $ #to end of a line
o ^ #to the beginning of a line
o G #end of a file
o :1 #to the beginning of a file
o :47 #to the given line (here on 47th line)
Editing file in vi editor
o dd #remove a line
o 5dd #remove 5 lines
o u #undo last action
o :s/string #searching a string in file
o :s/string/replace #search and replace a string in current line
o :%s/string/replace #search and replace a string in whole file
o :%s/string/replace/i #search and replace a string in whole file(Case Insensitive)
Introduction to PERL:
o PERL : Practical Extraction and Report Language
o Developed by Larry Wall in 1987
o It is a interpreted language
o Code written in Perl is called Perl Script
o Most recent version of Perl -Perl 5.24.3 released on 22-09-2017
Basic Syntax:
o Statements ends with semicolon (;)
o Comments starts with #
o Variables:
o You don’t have to declare a variable type
o Identifiers:
o A variable name
o Case Sensitive
o Example of perl Script :
#perl 5.22.1 ----------------- Perl version in comment
use strict; ----------------- Compiler flag for writing perl in strict way
use warnings; ----------------- Compiler flag for runtime warnings
print "Hello, World";-------------- Print statement for displaying output
 Save this file with .pl extention (say – Hello.pl)
 Execution of the Script : (on LINUX platform)
1. perl Hello.pl / perl –w Hello.perl
or
2. Make the perl file executable
chmod 700 Hello.pl
Execute with the following command:
./Hello.pl
Data types in Perl:
Perl language is a loosely typed language, the Perl interpreter itself chooses the data type
There are basically three data types in Perl
1. Scalars : Perl scalars are a single data item. A scalar can be a
number, a reference (address of a variable) or a string.
Scalars are preceded by ‘$’ sign.
Eg:- $name = “Sagar”;
$age = 24;
2. Arrays : Arrays are an ordered list of scalars.
They are preceded by ‘@’ sign.
Eg:- @arr = (1, 2, 3);
@arr_str = (“happy”, “new”, “year”);
3. Hashes : Hashes are an unordered collection of key-value pairs.
They are preceded by ‘%’ sign.
Eg:- %hashName = (
“Ram" => 24;
“Raman” => 26; );
User input in Perl Programming:
o For user input : <STDIN> or <>
Example : userInput.pl
#perl 5.22.1
use strict;
use warnings;
print "Enter your Name:n";
my $name = <STDIN>;
say "Welcome $name";
Execution: perl userInput.pl (Enter)
Output: Enter your Name:
Sagar
Welcome Sagar
String Operation Arithmetic
lt less than <
gt greater than >
eq equal to ==
le less than or equal to <=
ge greater than or equal to >=
ne not equal to !=
cmp compare, return 1, 0, -1 <=>
Comparison Operators:
Operator Operation
||, or logical or
&&, and logical and
!, not logical not
xor logical xor
Logical Operators
Operator Operation
. string concatenation
x string repetition
.= concatenation and assignment
$string1 = “Hello";
$string2 = “World";
$newstring = $string1 . $string2; #“HelloWorld"
$newerstring = $string1 x 2; #“Hello"
$string1 .= $string2; #“HelloWorld"
String Operators
Functions in Perl:
o Functions in Perl are known as Subroutines
o Subroutines are created with sub keyword
Example:
#!/usr/bin/perl
# Function definition
sub Hello {
print "Hello, World!n";
}
# Function call
Hello();
Predefined subroutines for Arrays:
Sr.No. Types & Description
1 push @ARRAY, LIST
Pushes the values of the list onto the end of the array.
2 pop @ARRAY
Pops off and returns the last value of the array.
3 shift @ARRAY
Shifts the first value of the array off and returns it, shortening the
array by 1 and moving everything down.
4 unshift @ARRAY, LIST
Prepends list to the front of the array, and returns the number of
elements in the new array.
Example for Arrays subroutines:
#perl 5.22.1
use strict;
use warnings;
my @arr;
print "Enter the number of element you want to enter n"; #Enter Size
my $n = <STDIN>;
print "n Enter the elements n"; # Enter Elements
for (my $i= 0; $i<$n; $i++){
my $ele = <STDIN>;
$arr[$i]=$ele;
}
print "Entered Elements are : --- n"; #print Elements
for (my $i= 0; $i<$n; $i++){
print $arr[$i];
}
print "Size of the array is : - ".scalar @arr."n"; # get Size
print "Your sorted array is : -n";
my @sorted_arr = sort(@arr); #sort Array
print @sorted_arr;
print "After Element pushingn";
push(@sorted_arr, "99n"); #add one Element at the end of array
print @sorted_arr;
print "New size of the array is :---".scalar @sorted_arr."n";
print "After unshifting ---- Adding element at begining n";
unshift (@sorted_arr,"555n"); #add element at the begining of the array
print @sorted_arr;
print "After poping ------ removing element from end n";
pop(@sorted_arr);
print @sorted_arr;
print "After shifting ------ removing element from beginning n";
shift(@sorted_arr);
print @sorted_arr;
OUTPUT:
Size of the array is : - 3
Your sorted array is : -
3
7
9
After Element pushing
3
7
9
99
New size of the array is :---4
After unshifting ---- Adding element at begining
555
3
7
9
99
After poping ------ removing element from end
555
3
7
9
After shifting ------ removing element from beginning
3
7
9
o File Handling :
Eg:
#perl 5.22.1
open(DATA, "<file.txt") or die "Couldn't open file file.txt, $!";
while(<DATA>) { print "$_"; }
o File opening modes:
Sr.No. Entities & Definition
1 < or r
Read Only Access
2 > or w
Creates, Writes, and Truncates
3 >> or a
Writes, Appends, and Creates
4 +< or r+
Reads and Writes
5 +> or w+
Reads, Writes, Creates, and Truncates
6 +>> or a+
Reads, Writes, Appends, and Creates
Regular Expression in Perl:
o There are three regular expression operator in Perl
1. Match Regular Expression - m//
2. Substitute Regular Expression - s///
3. Transliterate Regular Expression - tr///
Example: my $str = “Hello, World! Happy New Year ”;
Match operator : $str =~ m/Happy/ #true
Substitute operator: $str =~ s/World/India/; #will replace World with India(only first occurrence)
Translator operator: $str = ~tr/World/India/;#will replace all occurrence of World to India
Thank You

Linux And perl

  • 1.
  • 2.
    Introduction to Linux oOpen source Operating System o Developed by Linus Torvalds o Architecture of Linux operating system
  • 3.
    Linux Basic Commands: oSYSTEM & HARDWARE INFORMATION o USER INFORMATION AND MANAGEMENT o FILE AND DIRECTORY COMMANDS o PROCESS MANAGEMENT o FILE PERMISSIONS o NETWORKING o ARCHIVES (TAR FILES) o SEARCH o FILE TRANSFERS o DIRECTORY NAVIGATION
  • 4.
    System & HardwareInformation:- o uname –a #Display Linux system information Linux aa34faf8af0b 3.10.0514.26.2.el7.x86_64 #1 SMP Tue Jul 4 15:04:05 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux o uname –r #Dispaly kernel release information 3.10.0-514.26.2.el7.x86_64 o uptime #for how long system has been running 11:56:15 up 14 days, 21:18, 0 users, load average: 23.14, 24.23, 24.68 o hostname #gives hostname of the system cb.vu o hostname –I #gives IP address of the Host 78.31.70.238 o last reboot #to check when the system has been last rebooted wtmp begins Sat Sep 9 10:24:23 2017 o date #display the date and time Mon Jan 01 2018 17:17:33 GMT+0530 (India Standard Time) o cal #display current month calendar o free #Display the free and used memory (-h for human readable, -m for MB, -g for GB) total used free shared buff/cache available Mem: 263861664 11205028 205258364 1867876 47398272 233338992 Swap: 4194300 1756284 2438016
  • 5.
    User Information andManagement:- o w #show who is logged in and what they are doing. 12:07:00 up 14 days, 21:29, 0 users, load average: 21.66, 24.14, 24.30 USER TTY LOGIN@ IDLE JCPU PCPU WHAT o who #who is logged into the system o whoami #who are you logged in as [2018-01-01 17:41.43] ~ [SAGAR.workgroup] ➤ whoami SAGAR o id #display the current user id and group id [2018-01-01 17:41.49] ~ [SAGAR.workgroup] ➤ id uid=1001(SAGAR) gid=513(UsersGrp) groups=1002(HomeUsers),1004(ORA_DBA),559(Performance Log Users),545(Users) o last #who logged in last
  • 6.
    Files and DirectoriesCommands: o ls –al #lists all file in long listed format o ll #actually aliased to `ls -l' o pwd #shows present working directory o mkdir directory_name #creates a new directory o rmdir directory_name #deletes an empty directory o rm –r directory_name #deletes the directory and its contents o rm filename #deletes a file o cp file1 file2 #copy one file to another o mv file1 file2 #move a file/ rename a file o touch filename #create a new file o cat filename #displays the file contents
  • 7.
    File Permissions: • Thereare 3 types of users 1. User(u) 2. Group(g) 3. Others/ World(o) • Below are the permissions types • Read= r • Write= w • Execute = x • No access = - • Commands to change the permissions of the file:- chmod example:- chmod 755 filename 1/0 1/0 1/0 r = - - - w = - - - x = - - - Example: rwx rwx rwx chmod 777 filename
  • 8.
    Archives (Tar files): otar -cf archive.tar directory # Create tar named archive.tar containing directory. o tar -xf archive.tar # Extract the contents from archive.tar. o tar -czf archive.tar.gz directory # Create a gzip compressed tar file name archive.tar.gz. o tar -xzf archive.tar.gz # Extract a gzip compressed tar file. Directory Navigation: o cd .. # To go up one level of the directory tree. (Change into the parent directory.) o cd # Go to the $HOME directory o cd /etc # Change to the /etc directory o cd - # go back to previous directory (last accessed dir)
  • 9.
    Process Management: o ps#your currently running processes o ps –ef #all the currently running processes on the system o ps- -ef |grep processname #process information for process name o kill pid #kill a process o top #display and manage the top processes o killall processname #kill all processes named there o program & #start program in the background o bg #display stopped or background processes o fg #bring the most recent backgroungd job to foreground
  • 10.
    Networking: o ifconfig #Displaysnetwork interface and ip address o ping #to check given address is alive or not o dig domain_name #display DNS information for domain o dig –x IP_Address #Reverse lookup of IP_Address o host domain #display DNS IP address for domain o hostname #display the hostname [2018-01-01 19:06.49] ~ [SAGAR.workgroup] ➤ hostname workgroup o netstat #Display listening tcp and udp ports and corresponding programs [2018-01-01 19:11.20] ~ [SAGAR.workgroup] ➤ netstat Active Connections Proto Local Address Foreign Address State TCP 10.10.156.9:4280 hk2sch130022025:https ESTABLISHED TCP 10.10.156.9:4294 sb-in-f188:5228 ESTABLISHED TCP 10.10.156.9:6010 static:https ESTABLISHED TCP 10.10.156.9:9327 static:https ESTABLISHED TCP 10.10.156.9:9635 13.75.42.223:https TIME_WAIT
  • 11.
    SEARCH: o grep patternfile # Search for pattern in file o grep -r pattern directory # Search recursively for pattern in directory o locate name # Find files and directories by name o find /home/Dir -name 'prefix*’ # Find files in /home/Dir that start with "prefix". o find /home -size +100M # Find files larger than 100MB in /home File Transfer: o scp file.txt server:/tmp # Secure copy file.txt to the /tmp folder on server o scp server:/var/www/*.html /tmp # Copy *.html files from server to the local /tmp folder. o scp -r server:/var/www /tmp # Copy all files and directories recursively from server to the current system's /tmp folder.
  • 12.
    File Editing: o Mostcommon editor in Linux -- vi editor o Commands for editing files in vi editor o vi filename # to open file in editor (Command mode) o Press “i” # to go in INSERT mode o double esc # moving to command mode o :w #to save changes o :q #to exit o :q! #force exit o :wq #save changes and exit o Commands for movement inside a file o h, j, k ,l #left, down, up o $ #to end of a line o ^ #to the beginning of a line o G #end of a file o :1 #to the beginning of a file o :47 #to the given line (here on 47th line)
  • 13.
    Editing file invi editor o dd #remove a line o 5dd #remove 5 lines o u #undo last action o :s/string #searching a string in file o :s/string/replace #search and replace a string in current line o :%s/string/replace #search and replace a string in whole file o :%s/string/replace/i #search and replace a string in whole file(Case Insensitive)
  • 14.
    Introduction to PERL: oPERL : Practical Extraction and Report Language o Developed by Larry Wall in 1987 o It is a interpreted language o Code written in Perl is called Perl Script o Most recent version of Perl -Perl 5.24.3 released on 22-09-2017
  • 15.
    Basic Syntax: o Statementsends with semicolon (;) o Comments starts with # o Variables: o You don’t have to declare a variable type o Identifiers: o A variable name o Case Sensitive
  • 16.
    o Example ofperl Script : #perl 5.22.1 ----------------- Perl version in comment use strict; ----------------- Compiler flag for writing perl in strict way use warnings; ----------------- Compiler flag for runtime warnings print "Hello, World";-------------- Print statement for displaying output  Save this file with .pl extention (say – Hello.pl)  Execution of the Script : (on LINUX platform) 1. perl Hello.pl / perl –w Hello.perl or 2. Make the perl file executable chmod 700 Hello.pl Execute with the following command: ./Hello.pl
  • 17.
    Data types inPerl: Perl language is a loosely typed language, the Perl interpreter itself chooses the data type There are basically three data types in Perl 1. Scalars : Perl scalars are a single data item. A scalar can be a number, a reference (address of a variable) or a string. Scalars are preceded by ‘$’ sign. Eg:- $name = “Sagar”; $age = 24; 2. Arrays : Arrays are an ordered list of scalars. They are preceded by ‘@’ sign. Eg:- @arr = (1, 2, 3); @arr_str = (“happy”, “new”, “year”); 3. Hashes : Hashes are an unordered collection of key-value pairs. They are preceded by ‘%’ sign. Eg:- %hashName = ( “Ram" => 24; “Raman” => 26; );
  • 18.
    User input inPerl Programming: o For user input : <STDIN> or <> Example : userInput.pl #perl 5.22.1 use strict; use warnings; print "Enter your Name:n"; my $name = <STDIN>; say "Welcome $name"; Execution: perl userInput.pl (Enter) Output: Enter your Name: Sagar Welcome Sagar
  • 19.
    String Operation Arithmetic ltless than < gt greater than > eq equal to == le less than or equal to <= ge greater than or equal to >= ne not equal to != cmp compare, return 1, 0, -1 <=> Comparison Operators:
  • 20.
    Operator Operation ||, orlogical or &&, and logical and !, not logical not xor logical xor Logical Operators Operator Operation . string concatenation x string repetition .= concatenation and assignment $string1 = “Hello"; $string2 = “World"; $newstring = $string1 . $string2; #“HelloWorld" $newerstring = $string1 x 2; #“Hello" $string1 .= $string2; #“HelloWorld" String Operators
  • 21.
    Functions in Perl: oFunctions in Perl are known as Subroutines o Subroutines are created with sub keyword Example: #!/usr/bin/perl # Function definition sub Hello { print "Hello, World!n"; } # Function call Hello();
  • 22.
    Predefined subroutines forArrays: Sr.No. Types & Description 1 push @ARRAY, LIST Pushes the values of the list onto the end of the array. 2 pop @ARRAY Pops off and returns the last value of the array. 3 shift @ARRAY Shifts the first value of the array off and returns it, shortening the array by 1 and moving everything down. 4 unshift @ARRAY, LIST Prepends list to the front of the array, and returns the number of elements in the new array.
  • 23.
    Example for Arrayssubroutines: #perl 5.22.1 use strict; use warnings; my @arr; print "Enter the number of element you want to enter n"; #Enter Size my $n = <STDIN>; print "n Enter the elements n"; # Enter Elements for (my $i= 0; $i<$n; $i++){ my $ele = <STDIN>; $arr[$i]=$ele; } print "Entered Elements are : --- n"; #print Elements for (my $i= 0; $i<$n; $i++){ print $arr[$i]; } print "Size of the array is : - ".scalar @arr."n"; # get Size print "Your sorted array is : -n"; my @sorted_arr = sort(@arr); #sort Array print @sorted_arr; print "After Element pushingn"; push(@sorted_arr, "99n"); #add one Element at the end of array print @sorted_arr; print "New size of the array is :---".scalar @sorted_arr."n"; print "After unshifting ---- Adding element at begining n"; unshift (@sorted_arr,"555n"); #add element at the begining of the array print @sorted_arr; print "After poping ------ removing element from end n"; pop(@sorted_arr); print @sorted_arr; print "After shifting ------ removing element from beginning n"; shift(@sorted_arr); print @sorted_arr; OUTPUT: Size of the array is : - 3 Your sorted array is : - 3 7 9 After Element pushing 3 7 9 99 New size of the array is :---4 After unshifting ---- Adding element at begining 555 3 7 9 99 After poping ------ removing element from end 555 3 7 9 After shifting ------ removing element from beginning 3 7 9
  • 24.
    o File Handling: Eg: #perl 5.22.1 open(DATA, "<file.txt") or die "Couldn't open file file.txt, $!"; while(<DATA>) { print "$_"; } o File opening modes: Sr.No. Entities & Definition 1 < or r Read Only Access 2 > or w Creates, Writes, and Truncates 3 >> or a Writes, Appends, and Creates 4 +< or r+ Reads and Writes 5 +> or w+ Reads, Writes, Creates, and Truncates 6 +>> or a+ Reads, Writes, Appends, and Creates
  • 25.
    Regular Expression inPerl: o There are three regular expression operator in Perl 1. Match Regular Expression - m// 2. Substitute Regular Expression - s/// 3. Transliterate Regular Expression - tr/// Example: my $str = “Hello, World! Happy New Year ”; Match operator : $str =~ m/Happy/ #true Substitute operator: $str =~ s/World/India/; #will replace World with India(only first occurrence) Translator operator: $str = ~tr/World/India/;#will replace all occurrence of World to India
  • 26.