How about this?
#!/usr/bin/perl
use strict;
use warnings;
my @data = ("NULL", "NULL", 1, 3, 70, "NULL", "NULL", "NULL", "NULL",
+"NULL", 50, 1, "NULL", 4, "NULL", "NULL", 5, "NULL", "NULL", "NULL");
my @data_indices = grep { $data[$_] ne "NULL"; } (0 .. $#data);
if (@data_indices) {
# Phase 1, fill the edges
if ($data_indices[0] > 0) {
# Left edge
map { $data[$_] = $data[$data_indices[0]]; } (0 .. $data_indic
+es[0] - 1);
}
if ($data_indices[$#data_indices] < $#data) {
# Right edge
map { $data[$_] = $data[$data_indices[$#data_indices]]; } ($da
+ta_indices[$#data_indices] + 1 .. $#data);
}
# Phase 2, fill all gaps between values
for my $index (1 .. $#data_indices) {
my $difference = $data_indices[$index] - $data_indices[$index
+- 1];
if ($difference == 1) { next; }
# fill the first half with the leftmost data-element
map { $data[$_] = $data[$data_indices[$index - 1]]; } ($data_i
+ndices[$index - 1] + 1 .. $data_indices[$index] - $difference / 2);
+ #.. truncates, so /2 will work.
# ... and the last half with the rightmost data-element
map { $data[$_] = $data[$data_indices[$index]]; } ($data_indic
+es[$index - 1] + 1 + $difference / 2 .. $data_indices[$index] - 1);
+ #.. truncates, so /2 will work.
if (($difference % 2) == 0) {
# This gap does have an equidistant data-element (which wa
+s left-filled, so we'll need to overwrite)
my $middle_index = $data_indices[$index] - $difference / 2
+;
$data[$middle_index] = ($data[$middle_index - 1] + $data[$
+middle_index + 1]) / 2;
}
} ## end for my $index (1 .. $#data_indices)
} ## end if (@data_indices)
print (join (',', @data) . "\n");
This first indexes all non-NULL values, and then fixes the NULL-values step by step.
I'm using
map a lot, but you could implement that using foreach-loops if you find map tricky to parse.
Edit: added
if (@data_indices) to skip all work if @data contains only "NULL"-values or is empty.
Edit2: That was silly. Replaced @data-to-hash-to-ordered-array with a single grep.
-
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.