in reply to Searching through a file
Is this what the actual code looks like?
( See Writeup Formatting Tips for info on getting your code into the node. )#!/usr/bin/perl $string = 'test'; $inputs = 'test.txt'; open(TABLE, $inputs) or die "can't open $inputs.\n"; while ( $line = <IN> ) { if ( $_ =~ $string ) { print $_; } } close(IN);
If that's the case, then I see at least these problems at a glance:
You might try the below code (untested):
If, on the other hand, you want to just split on the first space instead of actually matching:#!/usr/bin/perl use strict; use warnings; my $string = 'test'; my $inputs = 'test.txt'; # see perlfunc open( my $in, '<', $inputs) or die "can't open $inputs.\n"; while ( <$in> ) { # see perlsyn, perlop if ( $_ =~ m/^$string(.*)/ ) { # see perlre print $1; # see perlvar, perlre } } close( $in ); # see perlfunc
perlvar, perlop, perlre, perlfunc are recommended reading. Also, if you're new to programming, consider Learning Perl. If you're a programmer new to Perl, consider Programming Perl.#!/usr/bin/perl use strict; use warnings; while ( <> ) { # takes filenames on the command line or STDIN if none print ( ( split )[1] ); }
BTW, Perl is a wonderful tool, but you might also want to 'man 1 cut' if you're using a Unixy OS.
Update: The code was missing a couple of $ sigils. Thanks to ikegami for pointing it out to me.
|
|---|