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

Hello everyone, I am writing a script where I have to take multi fasta file as input if I am using open() then its giveing me correct result, but if file name is not given in open() function then ask for user input. Can anyone please help me with user input. I am attaching my code

#!/usr/bin/perl use strict; use warnings; my $FILE; open (my $out, ">output.txt"); if (open $FILE, "<", 'chr.fa') { } else { print "Enter file name:\t"; $FILE=<STDIN>; } local $/ = ">"; my $count = 0; while (<$FILE>) { chomp; if ( $_ =~ /^(.*?)$(.*)$/ms) { my $header = $1; my $seq = $2; $seq =~ s/\s//g; while ( $seq =~ /([AAGC)/g) { print $out $1, "\n"; $count = $count +1; } } } print $out "$count sequences were found\n";

Replies are listed 'Best First'.
Re: if user provide input file use that in open() function instead
by hippo (Archbishop) on Nov 01, 2018 at 11:16 UTC

    You were almost there. You just needed to open the file which the user provided. Since this can also fail I prefer a loop. eg:

    #!/usr/bin/env perl use strict; use warnings; my $file = '/no_such_file.txt'; my $infh; while (not open $infh, '<', $file) { print "Could not open $file: $!. Please provide another:\n"; chomp ($file = <STDIN>); } my $first = <$infh>; print "First line of $file: $first"; close $infh; exit;

    Running this we see something like this:

    $ ./fo.pl Could not open /no_such_file.txt: No such file or directory. Please pr +ovide another: foobar Could not open foobar: No such file or directory. Please provide anoth +er: /etc/hosts First line of /etc/hosts: 127.0.0.1 localhost.localdomain local +host
Re: if user provide input file use that in open() function istead
by BillKSmith (Monsignor) on Nov 01, 2018 at 14:55 UTC
    hippo has answered your question. I would further recommend a prompt module such as IO::Prompt::Hooked. You can get capability similar to his without writing any code.
    #!/usr/bin/perl use strict; use warnings; use IO::Prompt::Hooked; my %opts = ( message => 'Enter namen of input fasta file', default => 'chr.fa', validate => sub {-e $_[0]}, error => 'File does not exist', ); open my $FILE, '<', prompt(%opts); open my $out, '>', 'output.txt'; ...;

    If your input file used the full afta spec, I would also recommend finding a module to parse it. Your code suggests that your file uses only a small part of the spec. In that case, your approach of parsing it with regular expressions is fine. However, I do see errors in both of your regexes. $header would always be a null string. $seq would contain the entire record. (I would need a copy of your file spec in order to suggest a correction.) Your second regex does not even compile. (probably a typo in your post).

    Bill