0

I have a bash shell script.

I know how to tokenize a string in Perl using split function. I know there is a method in Bash as well. I prefer using the Perl function.

How could, if possible, Perl be used in bash to split a string and store in array?

Let's say string = "myaddr@mail.com;my2ndaddr@mail.com"

brian d foy
  • 129,424
  • 31
  • 207
  • 592
PaulM
  • 345
  • 2
  • 11

3 Answers3

2

If you're asking if a perl array can be used in bash: no, that data resides in a different process.

Given:

string="myaddr@mail.com;my2ndaddr@mail.com"

In bash, use

IFS=";" read -ra addresses <<< "$string"

If you really really want to use split in perl, you can do

mapfile -t addresses < <(
    perl -sle 'print for split /;/, $emails' -- -emails="$string"
)

Both solutions result in

$ declare -p addresses
declare -a addresses=([0]="myaddr@mail.com" [1]="my2ndaddr@mail.com")

Docs: read, mapfile

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
1

You can do something like this

v="myaddr@mail.com;my2ndaddr@mail.com"
IFS=$'\n' a=( $(perl -nE 'say for split /;/' <<< "$v") )

then a contains the email addresses.

As email addresses cannot contain withe-spaces, you can ignore the IFS part (but this is for the more general case).

Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134
0

I'm not sure why you would do this, but this comes to mind:

  1. Create a separate Perl script that takes one argument.
  2. Splits the string.
  3. Prints each token to stdout.
  4. Invoke the script from bash and give it the string
  5. Capture the output in a bash array

Redirect output to a bash array

ragouel
  • 179
  • 4
  • 15