in reply to Search for a string in a file

word = ARGV.shift File.open( ARGV.shift, 'r' ) do |in| File.open( ARGV.shift, 'w' ) do |out| in.each do |line| if line.chomp! == word out.puts line end end end end

Just do that in Perl and Bob's your paternal male sibling.

The cake is a lie.
The cake is a lie.
The cake is a lie.

Replies are listed 'Best First'.
Re^2: Search for a string in a file
by bv (Friar) on Mar 01, 2010 at 19:57 UTC
    #!/usr/bin/perl -l my $word = shift; open my $in, '<', shift or die $!; open my $out, '<', shift or die $!; while (<$in>) { print $out $_ if $_ eq $word; } close $in; close $out;

    Howdy, Uncle Bob! Nice error checking!


    print map{substr'hark, suPerJacent other l',$_,1}(11,7,6,16,5,1,15,18..23,8..10,24,17,0,12,13,3,14,2,4);

      Ruby's File.open throws an exception which the default runtime behavior handles pretty well on its own (not to mention the error message includes the filename which yours doesn't), so yes.

      $ ruby -e 'File.open( ARGV.shift, "r" ) { |f| puts f.readlines }' nott +here -e:1:in `initialize': No such file or directory - notthere (Errno::ENO +ENT) from -e:1:in `open' from -e:1

      And if you're going to be that pedantic you might want to check for the error from print when you try and print to a filehandle you've opened for reading . . .

      The cake is a lie.
      The cake is a lie.
      The cake is a lie.

        Well played. Also it goes to show I need to learn some of these other languages better—I thought that was written in Python!


        print map{substr'hark, suPerJacent other l',$_,1}(11,7,6,16,5,1,15,18..23,8..10,24,17,0,12,13,3,14,2,4);