Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

sort not sorting 1

Status
Not open for further replies.

grazinggoat

Programmer
Mar 12, 2008
41
0
0
US
I am attempting to sort the contents of a file by the 5th position.

the file is in this order:

0:1:2:3:server1a2:5:6:7
0:1:2:3:server4a2:5:6:7
0:1:2:3:server8a2:5:6:7
0:1:2:3:server1a2:5:6:7

it should output:

server1a2
server1a2
server4a2
server8a2

But it returns the same order that in the infile.

Here is what I have coded from all I have read this should
work...

#!/usr/bin/perl

my $infile = "/home/user/mach.txt";

open(FILE, $infile) or die "Can't open file";
while(<FILE>){

my ( $0, $1, $2, $3, $machine_name,
$5, $6, $7) = split( /:/, $_);

my @machs = $machine_name;
my @sortedmachs = sort { $a cmp $b } @machs;


print "@sortedmachs\n";
}
close FILE;





 
Hi

There are multiple problems.
[ul]
[li]You can not use $0 and similar variables in [tt]my[/tt] statements.[/li]
[li]You can not assign value to $0 and similar variables.[/li]
[li]If you not need to properly assign all those values to variables, use [tt]undef[/tt] instead.[/li]
[li]Assigning scalar to array will make the array have a single element.[/li]
[li]Sorting a single element array is not really spectacular. You should collect the values and [tt]sort[/tt] outside the [tt]while[/tt] loop.[/li]
[/ul]
Perl:
[b]my[/b] [navy]@machs[/navy][teal];[/teal]

[b]while[/b] [teal]([/teal][green][i]<DATA>[/i][/green][teal])[/teal] [teal]{[/teal]
  [b]my[/b] [teal]([/teal] [b]undef[/b][teal],[/teal] [b]undef[/b][teal],[/teal] [b]undef[/b][teal],[/teal] [b]undef[/b][teal],[/teal] [navy]$machine_name[/navy] [teal])[/teal] [teal]=[/teal] [b]split[/b][teal]([/teal] [green][i]/:/[/i][/green][teal],[/teal] [navy]$_[/navy][teal]);[/teal]
  [b]push[/b] [navy]@machs[/navy][teal],[/teal] [navy]$machine_name[/navy][teal];[/teal]
[teal]}[/teal]

[b]my[/b] [navy]@sortedmachs[/navy] [teal]=[/teal] [b]sort[/b] [teal]{[/teal] [navy]$a[/navy] [b]cmp[/b] [navy]$b[/navy] [teal]}[/teal] [navy]@machs[/navy][teal];[/teal]
[b]print[/b] [green][i]"@sortedmachs\n"[/i][/green][teal];[/teal]

__DATA__
0:1:2:3:server1a2:5:6:7
0:1:2:3:server4a2:5:6:7
0:1:2:3:server8a2:5:6:7
0:1:2:3:server1a2:5:6:7

Next time please post your code between [tt][ignore]
Code:
[/ignore][/tt] and [tt][ignore]
[/ignore][/tt] TGML tags.

Feherke.
[link feherke.github.com/][/url]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top