FAQ 6.5 I put a regular expression into $/ but it didn't work. What's wrong?


PerlFAQ Server

This is an excerpt from the latest version perlfaq6.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .


6.5: I put a regular expression into $/ but it didn't work. What's wrong?

$/ has to be a string. You can use these examples if you really need to
do this.

If you have File::Stream, this is easy.

use File::Stream;

my $stream = File::Stream->new(
separator => qr/\s*,\s*/,

print "$_\n" while <$stream>;

If you don't have File::Stream, you have to do a little more work.

You can use the four-argument form of sysread to continually add to a
buffer. After you add to the buffer, you check if you have a complete
line (using your regular expression).

local $_ = "";
while( sysread FH, $_, 8192, length ) {
while( s/^((?s).*?)your_pattern// ) {
my $record = $1;
# do stuff here.

You can do the same thing with foreach and a match using the c flag and
the \G anchor, if you do not mind your entire file being in memory at
the end.

local $_ = "";
while( sysread FH, $_, 8192, length ) {
foreach my $record ( m/\G((?s).*?)your_pattern/gc ) {
# do stuff here.
substr( $_, 0, pos ) = "" if pos;


The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you'd like to help maintain the perlfaq, see the details in


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question