开发者

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

开发者 https://www.devze.com 2023-02-17 02:24 出处:网络
I have a String that looks like this:开发者_Go百科 $string = \"Tags: sweet, yummie, chocolate, dark\"

I have a String that looks like this:

开发者_Go百科

$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.


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'
        ];


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消