I've been trying to teach myself hashes and have come up with the following block of code to change a line in a pipe-deliminated flat file. I was wondering if my fellow monks here could give me some advice as to how I could make this code simpler more efficient etc. I'm also wondering if there are better ways to do the same function. All suggestions, comments, etc. would be appreciated! Thanks!
Stamp_Guy
#!/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 (<TEST>) {
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 s
+orting.
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)
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.