in reply to Trying to make a search

There are several problems with your code... As mdillon already pointed out you should chomp $input to remove the cr/lf. The other major error is in the following line:
print "${line}";
That should read $line and not ${line}.

Now I've fixed your code (you can see my fixes below) to make it functional, but it still isn't very "perl" looking and has some needless code.

#!/usr/bin/perl my $ans; my $currentline; my @data; print "Letter? "; $letter = <STDIN>; chomp $letter; open (DATA, "books.txt"); @data = <DATA>; $currentline = 0; foreach $data(@data) { $line = $data[$currentline]; # there are brackets around $cu +rrentline if ($line =~ /^$letter/i) { print $line; } $currentline++ }
Now here is a much more "perl-looking" implementation:
#!/usr/bin/perl -w use strict; print "Letter? "; my $letter = <STDIN>; chomp $letter; open (DATA, "books.txt") or die "error opening file $!"; my $line; foreach $line(<DATA>) { if ($line =~ /^$letter/i) { print $line; } } close DATA;

Replies are listed 'Best First'.
RE: Re: Trying to make a search
by ishamael (Beadle) on Jun 04, 2000 at 02:02 UTC
    hehe, on the idea of more "perl looking", in my opinion:
    #/usr/bin/perl -w use strict; print "Letter: "; chomp(my $letter = <STDIN>); open(DATA, "books.txt") or die "error opening file $!"; while(<DATA>) { if (/^$letter/i) { print; } }

    charlie schmidt
    ishamael@themes.org
    www.diablonet.net/~ishamael/
Re: Trying to make a search
by link (Novice) on Jun 04, 2000 at 01:12 UTC
    Since we're already picking nits and playing reductionists; here's removing a little more redundancy. Hopefully without crossing over and becoming obscure (versions involving map()/grep()-combos deliberately left as an excersice for the reader ;D)
    #!/usr/bin/perl -w
    
      use strict;
    
      print "Letter? ";
      my $letter = <STDIN>;   
      chomp $letter;
      open DATA, "books.txt" or die "open(books.txt) returned: $!\n";
      foreach my $line (<DATA>) {
        print $line if $line =~ /^$letter/i;
      }  
      close DATA;
    
      Grep is not obscure. It is much clearer than dumb loops that are really just low level implementations of list operations.
      #!/usr/bin/perl -w use strict; print "Letter? "; chomp(my $letter = <STDIN>); open DATA, "books.txt" or die "open(books.txt) returned: $!\n"; print grep {/^$letter/io} <DATA>;
      Of course, I kind of like something like
      perl -e 'print grep {/^a/io} <>' /usr/dict/words
      Try it, you'll like it too!
RE: Re: Trying to make a search
by Anonymous Monk on Jun 04, 2000 at 08:13 UTC
    > The other major error is in the following line:
    ><BR > print "${line}";
    >
    > That should read $line and not ${line}.

    Actually, it doesn't make a difference. ${line} is just as good (and sometimes better) as $line in double-quotish contexts.