[PATCH perlfaq5] "How can I manipulate fixed-record-length files?"

[email protected] (Iain Truskett)
Newsgroups perl.perlfaq.workers
Message-ID <[email protected]>
Heyo,

The attached patch stops the answer in question from using symbolic
references and instead gets to illustrate a nice use of hash slices.

I think it makes the code easier to read. I may be wrong =)


cheers,
-- 
Iain.
fixed.patch (text/plain, 1.7 KB)
Index: perlfaq5.pod
===================================================================
RCS file: /cvs/public/perlfaq/perlfaq5.pod,v
retrieving revision 1.29
diff -u -r1.29 perlfaq5.pod
--- perlfaq5.pod	12 Aug 2003 02:44:46 -0000	1.29
+++ perlfaq5.pod	22 Nov 2003 14:21:05 -0000
@@ -162,22 +162,23 @@
 
     # sample input line:
     #   15158 p5  T      0:00 perl /home/tchrist/scripts/now-what
-    $PS_T = 'A6 A4 A7 A5 A*';
-    open(PS, "ps|");
-    print scalar <PS>;
-    while (<PS>) {
-	($pid, $tt, $stat, $time, $command) = unpack($PS_T, $_);
-	for $var (qw!pid tt stat time command!) {
-	    print "$var: <$$var>\n";
+    my $PS_T = 'A6 A4 A7 A5 A*';
+    open my $ps, '-|', 'ps';
+    print scalar <$ps>;
+    my @fields = qw( pid tt stat time command );
+    while (<$ps>) {
+        my %process;
+        @process{@fields} = unpack($PS_T, $_);
+	for my $field ( @fields ) {
+	    print "$field: <$process{$field}>\n";
 	}
-	print 'line=', pack($PS_T, $pid, $tt, $stat, $time, $command),
-		"\n";
+	print 'line=', pack($PS_T, @process{@fields} ), "\n";
     }
 
-We've used C<$$var> in a way that forbidden by C<use strict 'refs'>.
-That is, we've promoted a string to a scalar variable reference using
-symbolic references.  This is okay in small programs, but doesn't scale
-well.   It also only works on global variables, not lexicals.
+We've used a hash slice in order to easily handle the fields of each row.
+Storing the keys in an array means it's easy to operate on them as a
+group or loop over them with for. It also avoids polluting the program
+with global variables and using symbolic references.
 
 =head2 How can I make a filehandle local to a subroutine?  How do I pass filehandles between subroutines?  How do I make an array of filehandles?
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.