W
Will
Hello!
I have some experience with a pascal in an intro to programming class, and I'm
trying to learn Perl. I wrote a bubble sort in Perl, but it is inelegant. I
believe I could use the tr/// operator to make this a better piece of code,
but I was at a loss as to how to do it! Please help! Thanks!
#!/usr/bin/perl
#sorted2.plx
use warnings;
use strict;
my $input="my.txt";
my $flag=0;
$_="";
#my $input=shift;
#my $output=shift;
open INPUT, "my.txt" or die "Couldn't open file $input: $\n";
open OUTPUT, ">issorted.txt" or die $!;
my @file=<INPUT>;
my $num=scalar @file;
my $count=0;
my $flag="";
my $temp1="";
my $temp2="";
while ($count<$num-1){
if (($file[$count]) gt ($file[$count+1])){
$temp1=$file[$count];
$temp2=$file[$count+1];
#switchem'
$file[$count]=$temp2;
$file[$count+1]=$temp1;
$flag=1;
}
$count++;
if ($flag && $count>=$num){$count=0; $flag="";}
}#exited while
#@file= sort @file;
print @file;
print OUTPUT @file;
I have some experience with a pascal in an intro to programming class, and I'm
trying to learn Perl. I wrote a bubble sort in Perl, but it is inelegant. I
believe I could use the tr/// operator to make this a better piece of code,
but I was at a loss as to how to do it! Please help! Thanks!
#!/usr/bin/perl
#sorted2.plx
use warnings;
use strict;
my $input="my.txt";
my $flag=0;
$_="";
#my $input=shift;
#my $output=shift;
open INPUT, "my.txt" or die "Couldn't open file $input: $\n";
open OUTPUT, ">issorted.txt" or die $!;
my @file=<INPUT>;
my $num=scalar @file;
my $count=0;
my $flag="";
my $temp1="";
my $temp2="";
while ($count<$num-1){
if (($file[$count]) gt ($file[$count+1])){
$temp1=$file[$count];
$temp2=$file[$count+1];
#switchem'
$file[$count]=$temp2;
$file[$count+1]=$temp1;
$flag=1;
}
$count++;
if ($flag && $count>=$num){$count=0; $flag="";}
}#exited while
#@file= sort @file;
print @file;
print OUTPUT @file;