Winter Is Overflowing
Winter Is Overflowing

Reputation: 61

Escaping semi-colon syntax in Perl

How can I escape a semi-colon (that's syntax ) in perl by only adding characters after it?

Say I have a line of code:

print "foo";

I want to add the following code after it so it can repeat 5 times:

print "foo"; x 5;

Is there anyway I can escape/ignore the semicolon (without altering the original piece of code) so it can be interpreted as:

print "foo" x 5;

Edit: This seems like too much of a hassle, better off to just nest the line in a for loop.

Upvotes: 1

Views: 455

Answers (3)

mob
mob

Reputation: 118605

 print "foo"; BEGIN{tie *STDOUT,'FiveTimer';sub FiveTimer::TIEHANDLE{bless{},'FiveTimer'}sub FiveTimer::PRINT{CORE::print STDERR $_[1] x 5}}

or more readably

 print "foo"; BEGIN{ tie *STDOUT,'FiveTimer' }
 sub FiveTimer::TIEHANDLE{bless{},'FiveTimer'}
 sub FiveTimer::PRINT{CORE::print STDERR $_[1] x 5}}

Upvotes: 0

clamp
clamp

Reputation: 3262

Here is an example using a source filter. In fact it alters the code before executing it so you don't have to do it yourself.

echo package FiveTimes; use Filter::Simple sub{s/;/x5;/g};1; > FiveTimes.pm

perl -MFiveTimes -e"print qq/foo/;"
foofoofoofoofoo

Upvotes: 1

GMB
GMB

Reputation: 222432

Seems like you just want to print "foo" 5 times ?

If yes, then :

use strict;
use warnings;
print "foo" for (1..5);

Yields :

foofoofoofoofoo

Upvotes: 3

Related Questions