Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl output successive string from array

I have an array I can print out as "abcd" however I am trying to print it as "a>ab>abc>abcd". I can't figure out the nested loop I need within the foreach loop I have. What loop do I need within it to print it this way?

my $str = "a>b>c>d";
my @words = split />/, $str;

foreach my $i (0 .. $#words) {
print $words[$i], "\n";
}

Thank you.

like image 452
audioboxer Avatar asked May 12 '26 03:05

audioboxer


2 Answers

You had the right idea, but instead of printing the word at position i, you want to print all the words between positions 0 and i (inclusive). Also, your input can contain multiple strings, so loop over them.

use warnings;

while (my $str = <>) {              # read lines from stdin or named files
  chomp($str);                      # remove any trailing line separator

  my @words = split />/, $str;      # break string into array of words
  foreach my $i (0 .. $#words) {
    print join '', @words[0 .. $i]; # build the term from the first n words
    print '>' if $i < $#words;      # print separator between terms (but not at end)
  }

  print "\n";
}

There are many other ways to write it, but hopefully this way helps you understand what's happening and why. Good luck!

like image 80
mwp Avatar answered May 14 '26 18:05

mwp


one liner:

perl -e '@a=qw(a b c d); for(@a) {$s.=($h.=$_).">"} $s=substr($s,0,-1);print $s'