Using perl, create a regular expression for each of the following: 1. Replace al
ID: 3839787 • Letter: U
Question
Using perl, create a regular expression for each of the following:
1. Replace all of the occurrences of a full line of # characters (ignoring leading or training spaces and lines with just 1 #) with the following: # ---------- #
2. Change any URL ending in .htm to end with .html
3. For any set of multiple words following an equal sign (=), place what follows the equal sign in quotes.
eg: a = bcd efg becomes a = "bcd efg"
eg: a = bcd remains a = bcd
4. Add a semicolon (;) to the end of every line
5. Every line beginning with a comment marker (#) and containing additional text should have one (and only one) space following the comment marker.
For example:
# some text becomes....
# some text
6. Replace any pattern in the form of [__UPPER-CASE CHARACTERS__] with (lower-case characters)
ie: Open square bracket + two underscores + upper-case text + two underscores + close square bracket
eg:[__SOMEDATA__] becomes [somedata]
7. Follow every "config section" with a comment that indicates the current section count:
For example:
[SVN] # Section: 1
[......] # Section: 2
etc.
Explanation / Answer
Hi,
Please find below the answers-
1.
#!/usr/bin/perl
use strict;
use warnings;
open my $fh,"<", "abc.txt" or die $!;
my $er='#';
while (my $line = <$fh>) {
$line =~ s/^(s+)$er+(s+)|' '/m /;
#$line =~ s/= ([a-zA-Z]+) ([a-zA-Z]+)+/= "$1 $2"/;
print $line;
}
2.
#!/usr/bin/perl
use strict;
use warnings;
open my $fh,"<", "abc.txt" or die $!;
my $er='#';
while (my $line = <$fh>) {
#$line =~ s/^$er+|' '/m/;
$line =~ s/.htm|' '/.html/;
print $line;
}
3.
#!/usr/bin/perl
use strict;
use warnings;
open my $fh,"<", "abc.txt" or die $!;
my $er='#';
while (my $line = <$fh>) {
#$line =~ s/^$er+|' '/m/;
$line =~ s/= ([a-zA-Z]+) ([a-zA-Z]+)+/= "$1 $2"/;
print $line;
}
4.
#!/usr/bin/perl
use strict;
use warnings;
open my $fh,"<", "abc.txt" or die $!;
my $er='#';
while (my $line = <$fh>) {
#$line =~ s/^(s+)$er+(s+)|' '/m /;
#$line =~ s/= ([a-zA-Z]+) ([a-zA-Z]+)+/= "$1 $2"/;
$line =~ s/(.*)|' '/$1 ;/;
print $line;
}
6.
#!/usr/bin/perl
use strict;
use warnings;
open my $fh,"<", "abc.txt" or die $!;
my $er='#';
while (my $line = <$fh>) {
#$line =~ s/^(s+)$er+(s+)|' '/m /;
$line =~ s/[__(.*)__]/[$1]/;
print $line;
}
Cheers,
Vinay Prakash Singh
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.