CGI Perl Question:
Download Questions PDF

Sort a word "system" in perl/shell without using built in functions output should be emssty?

Answers:

Answer #1
#!/usr/bin/perl

my $word = $ARGV[0];
$sortword = "";
$lastchar = "";

while($word =~ /(.)/g)
{
$lastchar = $1;
if( $sortword ) {
$flag = "";
$newsortword = "";
while($sortword =~ /(.)/g) {
if( $lastchar gt $1 || $flag
eq "charcovered") {

$newsortword =
$newsortword.$1;
$flag = "greater" if($flag
ne "charcovered")
}
else {
$newsortword =
$newsortword.$lastchar.$1;
$flag = "charcovered";
}
}
if( $flag ne "charcovered" ) {
$newsortword =
$newsortword.$lastchar;
}

$sortword = $newsortword;
}
else {
$sortword = $lastchar;
}
}

print $sortword."\n";

Answer #2
#!/usr/bin/perl

my $word = $ARGV[0]; chomp($word);

my @word = ($word =~ /(.)/g);
my @sorted = @word;
for (my $i = 0; $i <= $#sorted; ++$i) {

for (my $j = 1; $j <= @sorted; ++$j) {
if ($sorted[$i] gt $sorted[$j]) {
my $tmp = $sorted[$i];
$sorted[$i] = $sorted[$j];
$sorted[$j] = $tmp;
}
}
}
my $sorted = '';
$sorted .= $_ foreach (@sorted);
print "Given word is: $wordn";
print "Sorted word is: $sortedn";

Download CGI Perl Interview Questions And Answers PDF

Previous QuestionNext Question
How to sort dates in Perl?How to find a substring in a string without using substr built in functions, and print the substring found?