l i n u x - u s e r s - g r o u p - o f - d a v i s
L U G O D
 
Next Meeting:
October 7: Social gathering
Next Installfest:
TBD
Latest News:
Aug. 18: Discounts to "Velocity" in NY; come to tonight's "Photography" talk
Page last updated:
2001 Dec 30 16:57

The following is an archive of a post made to our 'vox-tech mailing list' by one of its subscribers.

Report this post as spam:

(Enter your email address)
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
> 


LinkedIn
LUGOD Group on LinkedIn
Sign up for LUGOD event announcements
Your email address:
facebook
LUGOD Group on Facebook
'Like' LUGOD on Facebook:

Hosting provided by:
Sunset Systems
Sunset Systems offers preconfigured Linux systems, remote system administration and custom software development.

LUGOD: Linux Users' Group of Davis
PO Box 2082, Davis, CA 95617
Contact Us

LUGOD is a 501(c)7 non-profit organization
based in Davis, California
and serving the Sacramento area.
"Linux" is a trademark of Linus Torvalds.

Sponsored in part by:
EDGE Tech Corp.
For donating some give-aways for our meetings.