Lounge For casual talk about things unrelated to General Motors. In other words, off-topic stuff. And anything else that does not fit Section Description.

who can help me figure out some PERL script?

Thread Tools
 
Old 11-07-2007, 11:22 PM
  #12  
Senior Member
Posts like a Camaro
 
1995BvSSE's Avatar
 
Join Date: Nov 2002
Posts: 1,109
Likes: 0
Received 0 Likes on 0 Posts
1995BvSSE is on a distinguished road
Default

By the way, if it were me, I'd write the script "more like this"

But the beauty of Perl is that it is quite flexible. Ask 5 Perl programmers to write something, you'll get 5 totally different scripts.

Code:
use strict;
use warnings;

#always declare variables, required with use strict
my $in;
my %myhash;
my @keyarray;
my @valarray;

#Take input from the user, tokenize the input and store it into a hash
#We make the loop "infinite" until the "last" condition is met below
while(true) {
	print "Enter a key/value pair separated by a colon\n(quit to finish)\t";
	$in = <STDIN>;
	chomp $in;
		
	#using a "last" statement here precludes the need to have the "initial" set of
	#duplicate logic in the beginning of the script. i.e., we'll leave the loop
	#once our exit criteria is met
	last if $in eq "quit";
	(my @result) = split(/:/, $in);

	#Always verify your input!
	#Note that in Perl, treating an array as a scalar will give you the size.
	if (@result != 2)
	{
		print "ERROR: input not understood\n"; 
	}
	else
	{
		$myhash{$result[0]} = $result[1];
	}
}


#iterate through each element in the hash in sorted fashion
foreach my $temp (sort keys %myhash) {
	#store the hash keys in keyarray
	push(@keyarray,$temp);
	#store the hash values in valarray
	push(@valarray,$myhash{$temp});
}

#Take elements off the end of the array, one at a time, thus reversed sorted order
while(@keyarray > 0) {
	print("Key: ".pop(@keyarray)." Value: ".pop(@valarray)."\n");
}

exit(0);
Related Topics
Thread
Thread Starter
Forum
Replies
Last Post
DADillac
Audio (and aftermarket electronics)
8
09-25-2008 05:28 PM
Drifty
Lounge
1
08-04-2007 02:59 AM
SSE14U24ME
Lounge
7
04-18-2004 05:10 AM
bonnie94ssei
Everything Electrical & Electronic
9
02-20-2004 04:48 PM
FiReDeViL
Lounge
9
08-23-2003 11:39 PM



Quick Reply: who can help me figure out some PERL script?



All times are GMT -4. The time now is 12:15 AM.