SoFunction
Updated on 2025-04-14

The solution to the problem of perl qw using spaces as delimiter

When creating an array in perl, you can use qw.

But there is a problem, if you want to create an array of 20 names, and each person's name is this form of "Join smith" and "Harry Potter" that means each name contains both the last name and the name. At this point, qw does not work. Because qw uses spaces as delimiters.

Here are some alternative solutions for your reference.

Plan 1:

Use the most original solution, that is, double quotes, to create arrays

Copy the codeThe code is as follows:

@names=("Join smith","Harry Potter"); 
print @names[0];

The results are as follows:
F:\>perl\ 
Join smith 
F:\>

Plan 2:

We can make a simple workaround. qw can only use spaces as delimiters, so we replace the spaces in the middle of the person's name with other characters.
@names=qw/Join_smith Harry_Potter/; 
# Then when we output, we replace the middle connector.

Copy the codeThe code is as follows:

@names[0]=~s/_/ /g; 
print @names[0];

The results are as follows;
F:\>perl\ 
Join smith 
F:\>

Plan 3:

Create with split function.

Copy the codeThe code is as follows:

#First we define a variable
$names="Join smith,Harry potter", 

#The split function is used here, here split//The split//between the two slashes is where you want to split. In this example, commas are used as the segmentation boundary.
my @names=split/,/,$names; 
rint @names[0];

The results are as follows:
F:\>perl\ 
Join smith 
F:\>