perl -p -i bak -e 's/search_str/replace_str/g' filename
-p Is name a named pipe?
-e Evaluate replacement string as expression
-g change all occurances of the pattern
-i ignore case in pattern
Or you can write the following code:
--replace.pl---
#!/usr/bin/perl
if(-e $ARGV[0])
{
$cmd = 'copy $ARGV[0] $ARGV[0].bak';
`$cmd`;
}
else
{
print 'File does not exist.\n';
exit;
}
open(INPUT,'$ARGV[0].bak') or die 'Cannot open file: $!\n';
open(OUTPUT,'>$ARGV[0]');
while(INPUT){
$_ =~ s/$ARGV[1]/$ARGV[2]/g;
print $_;
print OUTPUT $_;
}
close INPUT;
close OUTPUT;
2) How to implement stack in Perl?
Answer: Use puch() and pop() function in the perl
e.g. @myNames = ('Larry', 'Curly');
push(@myNames, 'Moe'); # it push a value onto the end of the array.
# @myNames = ('Larry', 'Curly', 'Moe');
$oneName= pop(@myNames); # it remove and return the last element of the array
# @myNames = ('Larry', 'Curly');
# $oneName = 'Moe'
shift() function is used to remove and return the first element from an array.
$oneName= shift(@myNames); # it remove and return the first element of the array
# @myNames = ('Curly', 'Moe');
# $oneName = 'Larry'
unshift() function is used to add a value or values onto the beginning of an array.
@myNames = ('Curly', 'Moe');
unshift(@myNames, 'Larry'); # @myName =('Larry', 'Curly', 'Moe')
3) What is Grep used for in Perl?
Answer:
@LIST = grep(EXPRESSION, @ARRAY);Perl's grep() function runs a regular expression on each element of an array, and returns only the elements that evaluate to true.
@myNames = ('Jacob', 'Michael', 'Joshua', 'Matthew', 'Alexander', 'Andrew');
@grepNames = grep(/^A/, @myNames); # @grepNames becomes ('Alexander', 'Andrew').
4) Explain the difference between 'my' and 'local' variable scope declarations?
Answer:
Both of them are used to declare local variables. The variables declared with 'my' can live only within the block and cannot gets it's visibility inherited functions called within that block. The "local" variables can live within the block and have its visibility in the functions called within the block.
5) What are the arguments w normally use for Perl interpreter?
Answer:
-e for execute
-c to compile
-d to call the debugger on the file specified
-T for traint mode for security/input checking
-W for show all warning mode
-w to show less warning
-strict pragma is used when you should declare variables before their use
6) What is it meants by '$_' ?
Answer:
It is a default variable which holds automatically, a list of arguments passed to the subroutine within parentheses.
No comments:
Post a Comment