#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    5
    Rep Power
    0

    Basic Perl Programming Help


    So I am trying to write a perl code that would read a file and then print the contents/lines in a reverse order but I am stuck

    The below is how far I have come. I would appreciate all inputs

    use strict;
    use warnings;

    # Open a .txt file

    open(seq1, "<seq1.txt") or die $!;

    #Assign open files to arrays

    my @seq1 = <seq1>;
    print "@seq1";

    #Read forwards and backwards

    sub read_forward_and_backward {
    # Takes a file name and a true/false value.
    # If true, the first line returned will be from end of file.
    my ($file_name, $read_from_tail) = @_;
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Apr 2009
    Posts
    1,954
    Rep Power
    1225
  4. #3
  5. !~ /m$/
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    May 2004
    Location
    Reno, NV
    Posts
    4,264
    Rep Power
    1810
    The three argument form of the open function is preferred. Not a big deal, just pointing it out as a good habit to get into.

    Since you are reading the whole file into memory in an array, the easiest solution is to use the reverse function.

    Code:
    #!/usr/bin/env perl
    use strict;
    use warnings;
    
    open my $fh, "<", 'seq1.txt' or die "Can't open file: $!";
    my @seq1 = <$fh>;
    print reverse @seq1;
    Reduced as:
    Code:
    #!/usr/bin/env perl
    use strict;
    use warnings;
    
    open my $fh, "<", 'seq1.txt' or die "Can't open file: $!";
    print reverse <$fh>;
    The script would be more versatile if you didn't hard-code in the name of the file. You can pass in your filename from the command line if you use the default file operator. And since there are no variables of any kind, you can even drop the pragmas. The script in its simplest form might be:
    Code:
    #!/usr/bin/env perl
    print reverse <>;

IMN logo majestic logo threadwatch logo seochat tools logo