Re: [vox-tech] newbie regexp question
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [vox-tech] newbie regexp question
On Fri, Sep 29, 2000 at 08:31:34AM -0500, Jay Strauss wrote:
> Micah,
>
> Basic Perl question, in your example:
>
> > #!/usr/bin/perl
> > undef $/; # slurp the file into a scalar
> > $contents = <>;
> > $contents =~ /$exactSequence/;
> > $beforeMatch = $`;
> > $match = $&;
> > $afterMatch = $';
>
> Since you don't identify the file (I'm not sure where the "<>" will read), lets
> say I had a file at /home/jstrauss/FileToBeRead.txt, how would I read an entire
> file into the variable?
<> will read from every file provided to it by the command line, or if
there aren't any, from standard input.
To read in a specific file:
open (FILE, '< /home/jstrauss/FileToBeRead.txt');
$contents = <FILE>;
close (FILE);
will do the trick.
>
> And what does "undef $/;" do?
As the comment says, undeffing $/ will activate "slurp-mode", which
means when you assign <> to a scalar, you will read the entire file
into a scalar, instead of only one line. If you don't want newlines,
you'll need to get rid of those, perhaps with:
$contents =~ tr/\n//d;
The way it works is, perl always reads one line in from the file when
you are assigning to a scalar - however, you can change perl's
definition of a line. The $/ variable holds the string which perl
understands to terminate lines in an input file, so if you undef it,
it won't recognize anything as a line terminator and will read the
whole file.
The way I did it was rather hackish - a better way to do it is:
$oldValue = $/;
undef $/;
... (do stuff) ...
$/ = $oldValue;
Ideally placing that last line directly after reading in the file's
contents, so you don't accidentally screw with other possible file
reading mechanisms you may be using.
Cheers,
Micah
>
> Jay Strauss
> jstrauss@bazillion.com
> (h) 773.935.5326
> (c) 312.617.0264
>
|