Proof of concept #!/usr/bin/perl --
BEGIN{
package PPI::Transform::ConditionalAssignment;
use strict;
use warnings;
use Params::Util qw{_STRING _INSTANCE};
use PPI::Transform ();
use parent 'PPI::Transform';
our $VERSION = '0.1'; # VERSION
sub document {
my $self = shift;
my $document = _INSTANCE(shift, 'PPI::Document') or return undef;
my $elements = $document->find( sub {
$_[1]->isa('PPI::Token::Operator') or return '';
$_[1]->content eq '?' or return '';
$_[1]->snext_sibling->isa('PPI::Token::Operator') or return ''
+;
$_[1]->snext_sibling->content eq '=' or return '';
return 1;
} );
return undef unless defined $elements;
return 0 unless $elements;
my $changes = 0;
foreach my $question ( @$elements ) {
my $symbol = $question->sprevious_sibling->clone;
my $equals = $question->snext_sibling;
$equals->insert_after( $symbol );
$symbol->insert_after( $question->remove );
$changes++;
}
return $changes;
}
1;
$INC{'PPI/Transform/ConditionalAssignment.pm'}=__FILE__;
} # BEGIN
package main;
use Filter::PPI::Transform 'PPI::Transform::ConditionalAssignment';
for my $foo ( 0 .. 1 ) {
my $bar = $foo;
$foo ?= 'one' : 'zero';
print "$foo\n";
$bar ?= ('one '.rand): ('zero '.rand);
print "$bar\n";
}
print "let me know " ? "should I stay" : "or should I go";
__END__
$ perl ppi-transform-conditional-assignment.pl
zero
zero 0.563323974609375
one
one 0.086761474609375
should I stay
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|