4

I am working on a perl module and looking for an output (string) of the form : a:value1 OR a:value2 OR a:value3 OR ...

The values value1, value2, value3... are in an array (say, @values).

I know we could use join( ' OR ', @values ) to create a concatenated string of the form: value1 OR value2 OR value3 OR ...

But as you see above, I need an additional a: to be prepended to each value.

What would be a neat way to do so?

1 Answer 1

5

You typically use map for these kinds of things:

#!/usr/bin/env perl
use strict;
use warnings;

my @array = qw(value1 value2 value3);
print join(" OR ", map "a:$_", @array),"\n";

Output:

a:value1 OR a:value2 OR a:value3

map is a simple looping construct, which is useful when you want to do apply some simple logic to every element of a list without making too much clutter of your code.

Sign up to request clarification or add additional context in comments.

4 Comments

While map may be implemented as a loop internally, its purpose is to provide a mapping or function that maps one list into another by transforming all the elements of the list according to the same rule. It isn't useful to think of it as a looping construct.
@Borodin: Looping construct was meant more as a concise way of describing what map does than a formal definition. If you can suggest another term, I'd be happy to update the answer.
Is is useful to regard it as looping if you carry over state from one iteration to the next, especially if the end result depends on the order of execution.
You say "It isn't useful to think of it as a looping construct." after explaining it is ("transforming all the elements"). (Should be "each", not "all", though. You know, like "for each", but it's "map each" here.)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.