Hello Friends Today, through this tutorial, I will tell you How to Get Youtube Video id From url Using Perl Script Code? Here's the Perl code to extract the YouTube video ID from a URL, using regular expressions and the `LWP::Simple` module:
use LWP::Simple;
use strict;
use warnings;
sub get_youtube_video_id {
my ($url) = @_;
# Check if URL is valid YouTube format
unless ($url =~ m/^https?:\/\/(?:www\.)?youtube\.com\/(?:(?:watch\?v=)|(?:embed\/))([^\?\&]+)/) {
return undef;
}
# Extract the video ID using capture group
my $video_id = $1;
return $video_id;
}
# Get user input
my $url = prompt "Enter YouTube video URL: ";
# Get the video ID
my $video_id = get_youtube_video_id($url);
if ($video_id) {
print "Video ID: $video_id\n";
} else {
print "Invalid YouTube video URL or unable to extract ID.\n";
}
Explanation.
1. `LWP::Simple` module: The code imports the `LWP::Simple` module for making HTTP requests.
2. `get_youtube_video_id` function:
- It takes the URL as input.
- It uses a regular expression to check if the URL matches a valid YouTube format:
- `https?://`: Matches either HTTP or HTTPS protocol.
- `(?:www\.)?`: Matches optional "www." in the domain name.
- `youtube\.com`: Matches the YouTube domain.
- `(?:watch\?v=|embed\/)`: Matches either "watch?v=" or "embed/" before the video ID.
- `([^\?\&]+)`: Capture group to capture the video ID (anything except `?` and `&` characters).
- If the URL format is valid, the first capture group (`$1`) is extracted as the video ID.
- If the URL is invalid, it returns `undef`.