Brethren,

while trying to "do it more than one way", I've stumbled across a weird behaviour of the ternary operator. I had this code which keeps only the recent input in history of Term::Readline:

if ($optimize_history) { # remove duplicities from history my @history = $term->GetHistory($file); my %history = map {$_ => 1} @history; my @new_history = (); for (reverse @history) { # in reverse order if ($history{"$_"}) { # if not remembered ye +t unshift @new_history, $_; # remember history l +ine delete $history{"$_"}; # and remove it } } $term->SetHistory(@new_history); # set history to new l +ist $term->WriteHistory($file); # save history } else { # only add new line to the history file $term->WriteHistory($file); }
after some refactoring (I especially didn't like the usage of so much variables/structures) I came up with something like that:
if ($optimize_history) { my @history = $term->GetHistory($file); my %history; # eliminate duplicates in history and keep only the most recent for(my $i=scalar(@history)-1;$i>=0;$i--) { $_ = $history[$i]; !$history{$_} ? $history{$_}=1 : splice(@history,$i--,1); } $term->SetHistory(@history); # set history to new list } $term->WriteHistory($file); # save history
to my big surprise, when I tried to refactor the ternary operator into
$history{$_} ? splice(@history,$i--,1) : $history{$_}=1;
I get an error message:
Can't modify splice in scalar assignment at ./history.pl line 35, near + "1;" Execution of ./history.pl aborted due to compilation errors.
Ehm...Uh? Why is that? Have I - again - been caught by some precedence issue?

Bye
 PetaMem


In reply to Ternary Operator: Condition-Negation by PetaMem

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.