Josh Laroche
Josh Laroche

Reputation: 11

How to determine the length of a variable in an array in Perl

I am trying to print to the terminal in all upper-case any word that at is least five characters long. My code is:

if (substr(@vdata, length(@vdata)-5, 5)) {
    print "@vdata"; 
}

It does not seem to be working. What am I doing wrong?

Upvotes: 0

Views: 127

Answers (3)

Dave Cross
Dave Cross

Reputation: 69264

Let's start by making you snippet into a complete, runnable program.

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

my @vdata = qw[this arrays has strings of different lengths];

if (substr(@vdata, length(@vdata)-5, 5)) {
    print "@vdata";
}

I've put some data into @vdata, but also (and probably more importantly) I've turned on strict and warnings. You should get into the habit of doing that for all of your code.

So what happens if we try to run this program?

$ ./vdata
length() used on @vdata (did you mean "scalar(@vdata)"?) at ./vdata line 8.

So there's your first problem. You're using the length function on an array. I get the idea that you're not thinking particularly clearly about what you're thinking. Your description of the problem seems rather vague.

I am trying to print to the terminal in all upper-case any word that at least five characters long.

I assume that you are storing the words in the array @vdata. So instead of getting the length of the array, you want to get the length of each individual element of the array. Let's start by setting up a loop to look at each element in the array.

foreach my $word (@vdata) {
  # Do something with $word
}

The code within the block is run once for each element in @vdata. And each time it is executed, the element is in $word. So let's print $word if it's five characters or more.

foreach my $word (@vdata) {
  say $word if length($word) >= 5;
}

(Actually, we've used say, not print, to get an automatic newline character.)

Running that prints:

arrays
strings
different
lengths

So we're on the right lines.

Now you want to print these words in upper case. That's easy, we just use the uc function.

foreach my $word (@vdata) {
  say uc $word if length($word) >= 5;
}

And now the program shouts at us.

ARRAYS
STRINGS
DIFFERENT
LENGTHS

I think perhaps you were trying to do too much in one go. Programming is far easier if you break your problem down into smaller chunks and work on solving one smaller problem at a time.

Upvotes: 0

dsm
dsm

Reputation: 10403

You are making simple things complicated. Try something like:

print uc $_ if length $_ > 5

Upvotes: 1

Hayden
Hayden

Reputation: 2808

Assuming that @vdata contains your list of words:

my @upper = map {length $_ > 5 ? uc $_ : ()} @vdata;
print "@upper";

Upvotes: 1

Related Questions