On Mon, Oct 19, 2015 at 07:48:06PM +0530, Prashant Thorat wrote: > Hi All,
Hello, > I have a file with multiple lines ,I want to assign all content to variable > & then want to work on it. > Like want to match pattern /window/ from it. > how can it is possible ? > for example - > > open ( F1 ,"file.txt") || die "$!"; You should always use strict and use warnings. They will catch a lot of gotchas that Perl will normally silently ignore. use strict; use warnings; You should prefer the 3-argument open() as a best practice because it's safer. Also, you should prefer lexical file handles. Note that there's no need to quote a variable in Perl (Perl is not a shell language; variable quoting is not necessary). die $! would suffice. That said, you should probably add some context to that error so that you know what failed. For example: open my $fh, '<', 'file.txt' or die "open: $!"; > $a=<F1>; You should avoid using $a or $b as variable names because they have special meaning (i.e., see perldoc -f sort). See `perldoc perlvar' for $/, the input record separator (AKA $INPUT_RECORD_SEPARATOR with use English). If set to undef then you can slurp in the whole file with one read. my $contents = do { local $/ = undef; <$fh>; }; > if (/window/i){print > "it is present\n"; > } It's best to avoid using the default variable, $_, because it can very easily be overwritten from a distance. You originally planned to put the contents into $a, but as noted above that's a bad practice. Instead, I read into $contents. We can match the contents of the file by binding the regex to the contents: if ($contents =~ /window/i) { print "Contents of file.txt matched window.\n"; } Even though a lexical file handle will automatically be closed when it goes out of scope it's still a good practice to manually close it and check for errors. close $fh or warn "close: $!"; Regards, -- Brandon McCaig <bamcc...@gmail.com> <bamb...@castopulence.org> Castopulence Software <https://www.castopulence.org/> Blog <http://www.bambams.ca/> perl -E '$_=q{V zrna gur orfg jvgu jung V fnl. }. q{Vg qbrfa'\''g nyjnlf fbhaq gung jnl.}; tr/A-Ma-mN-Zn-z/N-Zn-zA-Ma-m/;say'
signature.asc
Description: Digital signature