Jostein Berntsen <jber...@broadpark.no> writes:

> On 25.02.18,18:32, hw wrote:
>> Hi,
>> 
>> what is the best way to find out the depth of the last word within a
>> line?  "Depth of a word" means "how many other words occur before the
>> last one?".
>> 
>> 
>> The background is that I want to write a CLI.  The CLI shall know a
>> number of commands like 'show', 'set', 'alias' and so on.
>> 
>> Using Term::ReadLine, I want to have completion.  Since commands on a
>> line will need to occur in a particular order, I want to make it so that
>> the completion shows what can occur next depending on what is already on
>> the line.
>> 
>> For example, when the line is 'show', the completion must not display
>> 'show' as it would when the line is still empty, but 'settings tables
>> levels'.
>> 
>> To accomplish this, I figured I need to attribute every command with a
>> depth --- like 'show' and 'alias' have a depth of 0 and 'settings',
>> 'tables', and 'levels' have a depth of 1.
>> 
>> 
>> I´m aware that this only works for a rather simple CLI that doesn´t have
>> too many commands.  Maybe there is a better solution --- if you ever
>> configured a switch or a router that has a good CLI, you know what I´m
>> trying to do.
>> 
>
> There are some examples using ARGV here:
>
> https://www.cyberciti.biz/faq/howto-pass-perl-command-line-arguments/
>
> Can you use this? 

Not really, the words I get from the ReadLine functions are not
organized in an array.

I´ve come up with this function to compute the "depth" of a word:


sub get_depth {
  my $string = shift;

  $string =~ s/\s/ /g;
  $string =~ s/\s+/ /g;
  $string =~ s/^\s*//;
  $string =~ s/\s*$//;

  my $depth = 0;
  my $position = 0;
  while((my $start = index($string, ' ', $position)) != -1) {
    $position = $start + 1;
    $depth++;
  }

  return $depth;
}


This sucks because the function needs to do too much work.

Anyway, I found that my idea doesn´t work at all because things are much
more complicated than going by the "depth" of a command to figure out
which other commands may follow it.  The CLI needs to consider the
whole line to be able to show only those commands that may follow.

I don´t have an idea yet how to do this without pre-defining all
possible lines, using placeholders to create 'line descriptions'.  If
that is required, I would need to write some sort of internal
interpreter which converts the line descriptions into something that can
be used for completion.

That seems like an awful lot of work ...

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to