cored has asked for the wisdom of the Perl Monks concerning the following question:

Well i was bore so i tryed to do the excersises on the tutorial section of perlmonks i found this one: Write a program that prompts the user for the name of a file to open and then reads in the file line by line. When it has finished reading the file it should print the lines in reverse order with this solution:
#!/usr/bin/perl 2: 3: #this program prompts a user for the name of a source file 4: #and then reads from the file line by line. Once it is done 5: #reading the file it prints the lines of the file in reverse ord +er 6: 7: print "What is the name of the source file? "; 8: $file=<>; 9: chomp($file); 10: open FILE, "<$file"; 11: while(<FILE>){ 12: push @lines,$_; 13: } 14: foreach(reverse @lines){ 15: print $_; 16: } 17: close FILE;
the program is functional but i just think in this way
#!perl -w use strict; my $file; print "Enter a filename: "; chomp ( $file = <STDIN> ); open ( FILE, "$file" ); for (reverse (<FILE>)){ print; } close FILE;
i just want to know which is better is something like a perl golf :D, thx

Replies are listed 'Best First'.
Re: Better Way to Do It
by broquaint (Abbot) on May 17, 2003 at 22:22 UTC
    A couple of things, you don't need to quote variables in perl as you might in the shell and you might want to check for the existence of the file. Here's my take on the exercise
    { print "Enter filename: "; chomp($f = <STDIN>); print "invalid file" and redo unless -f $f and -r $f; } open(f) and print reverse <f>;
    A little idiomatic admittedly, but that's fine by me :)
    HTH

    _________
    broquaint

      Your solution is less powerful than other presented solutions. Due to your explicite requirements only standard files can be given, your program can't unleash the power of the magical open. Your program can't reverse text given on standard input, or what comes from a pipe.

      Abigail

        Your solution is less powerful than other presented solutions
        Since the exercise was to print a file in reversed order, and that's what my code does, I'm hardly going to be loosing any sleep over this ;)
        HTH

        _________
        broquaint

Re: Better Way to Do It
by Chady (Priest) on May 18, 2003 at 11:33 UTC
    just for fun:
    print "Enter filename: "; my $file = <>; print `tac $file`;
    Note: epyt doesn't work as you expect under DOS. ;)
    He who asks will be a fool for five minutes, but he who doesn't ask will remain a fool for life.

    Chady | http://chady.net/