in reply to checking existence of a tag in a TK::Text?

G'day jsteng,

If you create all tags once and they're stable, you could create a hash and then use exists:

my %tag_for = map { $_ => 1 } $text->tagNames; ... later ... if (exists $tag_for{$j}) { ... }

If your tags are in constant flux (i.e. being added and removed) you could use grep to check for existence:

if (grep $_ eq $j, $text->tagNames) { ... }

If you used last in your foreach loop for efficiency reasons, take a look at List::Util::first. You might want to Benchmark though: first only allows the "function BLOCK LIST" format:

first { $_ eq $j } $text->tagNames

grep allows that format as well as the "function EXPR, LIST" format (which I've shown above). The BLOCK style is typically slower than the EXPR style (certainly for grep, map, and maybe others).

By the way, I'm not aware of any built-in method like:

$text->does_tag_exist($tag_name)

but perhaps someone else does.

— Ken

Replies are listed 'Best First'.
Re^2: checking existence of a tag in a TK::Text?
by jsteng (Beadle) on Apr 29, 2018 at 09:24 UTC
    @Ken,
    I like your hash idea!!!

    It is true, those tags are constantly created and deleted; but only *when* the user deletes or adds line manually, creating hashes should not slow down the app nor inconvenience the user experience.

    thanks!