[olug] Unix Tip: USING PERL TO REVERSE

Jay Hannah jay at jays.net
Fri Jun 13 20:23:25 UTC 2003


On Fri, 13 Jun 2003, Unix Guru Universe wrote:
> Yet another file reversal
> (I don't know many apps
> that need this, though!):
>
> perl -e 'print reverse <>' filename

Wow. I still learn something new every day. I never took the time to
"learn" about <> until just now. From perldoc perlop:

       The null filehandle <> is special: it can be used to emu-
       late the behavior of sed and awk.  Input from <> comes
       either from standard input, or from each file listed on
       the command line.  Here's how it works: the first time <>
       is evaluated, the @ARGV array is checked, and if it is
       empty, "$ARGV[0]" is set to "-", which when opened gives
       you standard input.  The @ARGV array is then processed as
       a list of filenames.  The loop


           while (<>) {
               ...                     # code for each line
           }

       is equivalent to the following Perl-like pseudo code:

           unshift(@ARGV, '-') unless @ARGV;
           while ($ARGV = shift) {
               open(ARGV, $ARGV);
               while (<ARGV>) {
                   ...         # code for each line
               }
           }

       except that it isn't so cumbersome to say, and will actu-
       ally work.  It really does shift the @ARGV array and put
       the current filename into the $ARGV variable.  It also
       uses filehandle ARGV internally--<> is just a synonym for
       <ARGV>, which is magical.  (The pseudo code above doesn't
       work because it treats <ARGV> as non-magical.)

Neato!

(Neat, but probably not something I'd use except in perl -e command line
one-liners.)

Jay Hannah
Omaha Perl Mongers: http://omaha.pm.org






More information about the OLUG mailing list