简体   繁体   中英

Perl: How do I split AND cut a given String?

I have a String that looks like this:

$string = "Tags: sweet, yummie, chocolate, dark"

I want to insert these Tags in a Mysql table.

  • So how do I cut the [Tags:] out of the string?

  • And how can I add foreach $string in a Mysql-table?

Start by removing the "Tags: " with a regex, and then split on ", ".

my $string = "Tags: sweet, yummie, chocolate, dark"
$string =~ s/Tags: //;
my @tags = split /, /, @string;

For the MySQL connection, you could use DBI::MySQL.

There is a split function in Perl.

The split function is used to split a string into smaller sections. You can split a string on a single character, a group of characers or a regular expression (a pattern).

You can also specify how many pieces to split the string into.

If your Tags always end with column : , you could do somethong like:

#!/usr/bin/perl
use Modern::Perl;
use Data::Dumper;

my $string = "Tags: sweet, yummie, chocolate, dark";
my @parts = split/[:,]\s*/,$string;
say Dumper \@parts;

output:

$VAR1 = [
          'Tags',
          'sweet',
          'yummie',
          'chocolate',
          'dark'
        ];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM