Sam’s Network Simulation Cradle Blog

23 Apr 2007

Silly Perl thoughts…

Filed under: General — sammydre @ 8:44 pm

A simple script to show a table of contents like view of a latex file. I could make a couple of assumptions about the input based on my setup. My first attempt which is probably somewhere on my blog looked like this:

Perl:
  1. if($#ARGV > 0) { $in_file_name = shift; }
  2. else { $in_file_name = "thesis.tex"; }
  3.  
  4. sub read_file
  5. {        
  6.     my $file_name = shift;
  7.     local *IN;
  8.     open IN, "<$file_name";
  9.  
  10.     while(<IN>) {
  11.         if(/^\\chapter.?{(.+?)}/) {print "——————–\n$1\n";}
  12.         elsif(/^\\section.?{(.+?)}/) {print " . . $1\n";}
  13.         elsif(/^\\subsection.?{(.+?)}/) {print " . . . . $1\n";}
  14.         elsif(/^\\subsubsection.?{(.+?)}/) {print " . . . . . . $1\n";}
  15.         elsif(/^\\paragraph.?{(.+?)}/) {print " . . . . . . . . $1\n";}
  16.         elsif(/^\\input{(.+?)}/) {read_file($1);}
  17.     }
  18.  
  19.     close IN;
  20. }  
  21.  
  22. read_file($in_file_name);

A classic recursive solution using a function. I had a quick play today and produced this:

Perl:
  1. #!perl -n
  2.  
  3. /^\\chapter.?{(.+?)}/       and print "-" x20 . "\n$1\n" or
  4. /^\\section.?{(.+?)}/       and print " ." x2 . " $1\n" or
  5. /^\\subsection.?{(.+?)}/    and print " ." x4 . " $1\n" or
  6. /^\\subsubsection.?{(.+?)}/ and print " ." x6 . " $1\n" or
  7. /^\\paragraph.?{(.+?)}/     and print " ." x8 . " $1\n" or
  8. /^\\input{(.+?)}/           and system "perl list_sections2.pl $1";

Which is a lot more compact. It’s almost inefficient, but this doesn’t really matter for this problem (or at least the input I have).

Which one feels more Perl-y?

Or should I just give up on Perl and go back to my Pythonic ways?

No Comments »

No comments yet.

RSS feed for comments on this post.

Leave a comment

Powered by WordPress