#!/usr/bin/perl -w use strict; # Predeclare variables. my %test; my @fileData; my @sorted; # Initialize the variable that will hold the data to be changed. my $change = "this is cool"; # Open the file open(TEST, "test.txt") || die "File couldn't be opened for reading: $!"; # Create a hash while () { my ($key,@fileData) = split /\|/; chomp @fileData; $test{$key} = \@fileData; } # Change the data $test{mykey}->[1] = "$change"; # Place all the hash data into an array of pipe-seperated values for sorting. foreach my $key (keys %test) { push (@sorted, "$key|$test{$key}->[0]|$test{$key}->[1]|$test{$key}->[2]|$test{$key}->[3]"); } # Sort the data by the number in the last part of the array. @sorted = map $_->[1], sort { $a->[0] <=> $b->[0] } map [ substr($_,rindex($_,'|')+1), $_ ], @sorted; # Put the line breaks back in. for (@sorted) { $_ = "$_\n"; } open(TEST, ">test.txt") || die "File couldn't be opened for writing: $!"; print TEST @sorted; close(TEST)