Re: Interpolate variable in a __DATA__ block
- From: rob.dixon@xxxxxxx (Rob Dixon)
- Date: Sat, 29 Mar 2008 20:26:35 +0000
Trudge wrote:
>
Hi Trudge.
I'm trying to get a script to interpolate variable values in a
__DATA__ block if possible. This is a kind of alternative to a full-
blown template method. I'm not sure if I can even do what I want,
hence my posting here.
No, you can't do that. But see below.
The following code only goes so far. It correctly prints the value of>
$$dataref each time GetData is called, but not in the while loop.
This is where I'm stuck.
8<--------------------->
#! /usr/bin/perl
use strict;
use warnings;
my @Blocks=qw(first second third);
foreach my $block (@Blocks)
{
GetData($block);
}
sub GetData
{
my $data=shift;
my $dataref=\$data;
print "\$\$dataref is: $$dataref\n";
while (<DATA>)
{
chomp;
if ($_ eq "<$data>")
{
next;
print "$_\n";
This print line is unreachable. The next statement before it will
transfer processing back to the beginning of the while loop.
}
if ($_ eq "</$data>")
You should consider using elsif here as the two conditions are mutually
exclusive.
{
last;
}
print "$_\n";
This line will be executed for every line that doesn't look like either
<first> or </first> etc. So, for this data, 'This is the $$dataref
chunk.' will be printed three times. You might want to check out the
range operator, described in perldoc perlop.
Also, $_ here is set as if you had written
$_ = 'This is the $$dataref chunk.';
so no interpolation will take place, and you will get the data line
printed exactly as it is.
}
}
__DATA__
<first>
This is the $$dataref chunk.
</first>
<second>
This is the $$dataref chunk.
</second>
<third>
This is the $$dataref chunk.
</third>
Without knowing what it is you are trying to do it is hard to know how
to help. Do you have reasons for avoiding the 'full-blown template
method'? Or perhaps here-documents would help you? You can learn about
them at
perldoc perlop
Or are you processing XML? There are modules specifically for that
purpose.
HTH,
Rob
.
- References:
- Interpolate variable in a __DATA__ block
- From: Trudge
- Interpolate variable in a __DATA__ block
- Prev by Date: Re: sort without ignoring hyphens
- Next by Date: Automate a search query from a website
- Previous by thread: Interpolate variable in a __DATA__ block
- Next by thread: Re: Interpolate variable in a __DATA__ block
- Index(es):